0

I'm trying to create some nested fields in $group stage of aggregation. I get the error that "stats" must be an accumulator. Is there any way to insert these nested fields?

model.aggregate( [ {
  $group: {
    _id: '$groupName,
    nestedFields: {
      field1: {
        $sum: { $multiply: [ '$num1', '$num2'] }
      },
      field2: { $sum: '$num3' }
    }
  }
} ] )

Any help is greatly appreciated.

edit: some sample data INPUT:

{
  "groupName": 1
  "num1": 2,
  "num2": 4,
  "num3": 8,
}
{
  "groupName": 1
  "num1": 2,
  "num2": 7,
  "num3": 1,
}
{
  "groupName": 2
  "num1": 1,
  "num2": 3,
  "num3": 5,
}
{
  "groupName": 2
  "num1": 6,
  "num2": 1,
  "num3": 2,
}

should OUTPUT through the aggregation:

{
  "_id": 1,
  "nestedFields": {
    "field1": 22,      // 2*4 + 2*7
    "field2": 9,       // 8 + 1
  }
},
{
  "_id": 2,
  "nestedFields": {
    "field1": 9,      
    "field2": 7,       
  }
}
6
  • 1
    You need to do it in the next stage with $addFields or $project Commented Mar 30, 2020 at 7:22
  • can you share your request data and response data ? if not solve your problem Commented Mar 30, 2020 at 7:42
  • Basicaly i have to save the values in common fields in $group, nest them in $addFields and remove the original ones in $project. Isnt there a better way @Valijon ? Commented Mar 30, 2020 at 7:42
  • @MaheshBhatnagar It's too much. I will edit the question to make it a bit simpler. Commented Mar 30, 2020 at 7:45
  • But i want to request data@ KFaidon K. Commented Mar 30, 2020 at 7:48

1 Answer 1

1

During $group stage, MongoDB does not allow create nested fields.

Workaround: You need to store aggregated values in ordinary fields and in the next stage, transform into desired result with $project operator.

model.aggregate([
  {
    $group: {
      _id: "$groupName",
      field1: {
        $sum: {
          $multiply: [
            "$num1",
            "$num2"
          ]
        }
      },
      field2: {
        $sum: "$num3"
      }
    }
  },
  {
    $project: {
      nestedFields: {
        field1: "$field1",
        field2: "$field2"
      }
    }
  }
])

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.