0

I have the following document :

{
 _ids : ...
 market : ...
 contractorName : ...
 field :...
 amount : ...
}

and i want to group it first by market then group the result by field (sum of amounts) inside each obtained list as follow :

{
 [
  market : ...
  result : [
            {
             field : ...
             sumOfAmounts : ...
            }
          ]
 ]
}

any idea how to acheive this using springboot mongotemplate or by using raw mongo

1 Answer 1

2

Group both market and field first, then group market.

You should group them twice.

And try "Reverse Thinking" of group.

db.collection.aggregate([
  {
    $group: {
      _id: {
        market: "$market",
        field: "$field"
      },
      sumOfAmounts: {
        $sum: "$amount"
      }
    }
  },
  {
    $group: {
      _id: "$_id.market",
      result: {
        $push: {
          field: "$_id.field",
          sumOfAmounts: "$sumOfAmounts"
        }
      }
    }
  },
  {
    $set: {
      market: "$_id"
    }
  }
])

mongoplayground

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

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.