Anil Yadav
Anil Yadav

Reputation: 35

How to Add Multiple Documents into one document in MongoDB?

assume I have these three documents in a collection

{ "num" : 10, "count" : 1 }
{ "num" : 20, "count" : 2 }
{ "num" : 30, "count" : 3 }

Now I want to make one documents with sum of same fields(fields are same in all doc)

{ "num" : 60, "count" : 6 }

How to do that ?

Upvotes: 0

Views: 35

Answers (1)

mc-user
mc-user

Reputation: 2071

You can write an aggregate query to do that.

  1. Use $group with $sum to calculate the sum
  2. Use projection's $project operator to remove the id key required by the $group operator
db.collection.aggregate({
  $group: {
    _id: "",
    num: {
      $sum: "$num"
    },
    count: {
      $sum: "$count"
    }
  }
},
{
  $project: {
    _id: 0,
    num: "$num",
    count: "$count"
  }
})

Playground link

Upvotes: 1

Related Questions