3

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 3

4

For .find() query, you can direct use the $sum operator.

db.collection.find({},
{
  catalog: 1,
  totalSum: {
    $sum: "$book.price"
  },
  totalPromo: {
    $sum: "$book.promo"
  }
})

Sample Mongo Playground

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, this answer provides the sum of the book array for each document (calculate under each document). If you are looking for sum based on the catalog, you need the aggregation query with $group which covers in the other answer.
3

use aggregate

db.getCollection('myCollection').aggregate([
    { "$group": {
        "_id": "$tempId",
        "totalPrice": { 
            "$sum": { "$sum": "$book.price" } 
        },
        "totalPromo": { 
            "$sum": { "$sum": "$book.promo" } 
        }
    } }
])

Comments

0

Using $group (aggregation)

db.getCollection('catlog').aggregate([{ 
    $group: {
        _id: "$_id",
        catalog: { $first: "$catalog" },
        totalPrice: { "$sum": { $sum: "$book.price" } },
        totalPromo: { "$sum": { $sum: "$book.promo" } }
    }
}])

Output will be:

{
    "_id" : ObjectId("6247b33cffc5b6f714769fbb"),
    "catalog" : "A",
    "totalPrice" : 120000,
    "totalPromo" : 30000
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.