Mbanda
Mbanda

Reputation: 1018

mongodb multiple aggregates in same query, each with total

Trying to do aggregate group with more than one { $sum: '$total' }

db.transactions.aggregate([{$group: {_id: '$cashier', cost: {$sum: "$total"}}}, {$group:
{_id: '$deviceid', cost: {$sum: "$total"}}}  ])

When i use two aggregates, the second aggregate returns 0. Av tried to use $project but still i loose get zero.

Upvotes: 0

Views: 48

Answers (1)

Valijon
Valijon

Reputation: 13103

You need to use $facet

db.transactions.aggregate([
  {
    $facet: {
      cashier: [
        {
          $group: {
            _id: "$cashier",
            cost: {
              $sum: "$total"
            }
          }
        }
      ],
      deviceId: [
        {
          $group: {
            _id: "$deviceid",
            cost: {
              $sum: "$total"
            }
          }
        }
      ]
    }
  }
])

MongoPlayground

Upvotes: 2

Related Questions