'I need to $multiply two elements in an array, but the problem is one of the element is a string, so how can i change it to an integer
**`{
$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**
}
Solution 1:[1]
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']}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | xx.author |
