Hi I’m very new to MongoDB, I’m trying to get the total price and promo of the below MongoDB data with document.collection.find
and $add
functionality:
Data:
[
{
"catalog":"A",
"book":[
{
"title":"Mermaid yang terdampar",
"price":90000,
"promo":15000
},
{
"title":"Srigala berbulu domba",
"price":30000,
"promo":15000
}
}
]
And my expected result would be sth like this:
[
{
"catalog": "A",
"totalPrice": 140000,
"totalPromo": 32000
},
]
Does anybody ever encounter a similar issue? I’m confused with the query 🙂
3
Answers
use aggregate
For
.find()
query, you can direct use the$sum
operator.Sample Mongo Playground
Using $group (aggregation)
Output will be: