Home > Software design >  How to $push all of the document in aggregation instead of specific field?
How to $push all of the document in aggregation instead of specific field?

Time:04-29

I have this array of results in the first stage of the aggregation pipeline, using a $match:

[
  { a: 1, b: 2 },
  { a: 3, b: 4 }
]

Now I want to sum all of the A's and B's and also still have them so I will have something like this as a result:

{
  total_sum: 10,
  items: [...] // first and second objects ofcourse
}

I have tried to $group and $push, however, push only pushes specific fields from the object and I need to name A and B, instead just of parse all of them.

How can I do it?

CodePudding user response:

  1. $set - Create new field total to sum a and b.
  2. $group - Group by null, indicate to sum all total and add the document in items array.

With $$ROOT it will add the whole document.

items: {
  $push: "$ROOT"
}

If you want just some fields only, then specify the (desired) document pattern.

items: {
  $push: {
    A: "$a",
    B: "$b"
  }
}
  1. $unset (If use $push $$ROOT) - Remove total field from items field.
db.collection.aggregate([
  {
    $set: {
      total: {
        $sum: [
          "$a",
          "$b"
        ]
      }
    }
  },
  {
    $group: {
      _id: null,
      total_sum: {
        $sum: "$total"
      },
      items: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $unset: "items.total"
  }
])

Sample Mongo Playground

  • Related