Home > Back-end >  I need to $multiply two elements in an array, but the problem is one of the element is a string, so
I need to $multiply two elements in an array, but the problem is one of the element is a string, so

Time:04-25

**`{
       $project: {
                     item:1,quantity:1, product: { $arrayElemAt: ['$products.price',0] }
                 }
   },
   {
       $project: {
                     item:1,quantity:1, total : {$multiply:['$product','$quantity']}
                 }
    }`**

here the $product is a string of numbers and the $quantity is an integer.

i tried using parseInt('$product') and the output was:

{
    _id: new ObjectId("626030ccb52876d4dd779dac"),
    item: new ObjectId("6260352755ed2b52b2ff13a0"),
    quantity: 3,
    total: **NaN**
  }

CodePudding user response:

Using **$toInt**, we can change It:

{
                        $project: {
                            item:1,quantity:1, product: { $toInt :{ $arrayElemAt: ['$products.price',0] }}
                        }
                    },
                    {
                        $project: {
                            item:1,quantity:1, total : {$multiply:['$product','$quantity']}
                        }
                    }
  • Related