0

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.

1 Answer 1

2

You need to use $facet

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

MongoPlayground

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

2 Comments

Bravooh ! I have removed $project and now using $face. It works well. But just point of curiosity. Which of this 2 is reliable for heavy Load calls.
The $facet pipeline stage would cause problem with the BSON Limit only.

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.