Nested accumulator in Aggregation Grouping

In my document, I have a couple of fields in a nested document that I want to aggregate

{
    field1:111,
    field2:222,
    nested:{
        field3:333,
        field4:444
    }
}

I need the output of $group to be in the similar nested structure. I need their $avg values to be accumulated in the nested document itself.
When I try to use the field name as nested.field3 and nested.field4, it throws error.

The field name ‘nested.field3’ cannot contain ‘.’

Is there any operator that will let me do this?

PS: I dont want to add a project stage to do this.

It would help us help you if you could share the error you are having.

Its the standard error:

The field name ‘nested.field3’ cannot contain ‘.’

Its definitely not allowed this way. So I need to know if there is any operator that does it, or its not possible in group stage at all.

Can you post what you tried?

Sorry, I thought I was clear in the question.

Here’s what I have tried:

db.col.aggregate([{
    $group:{
        _id:null,
       "nested.field3":{ $avg:"$nested.field3"}
    }
}])

and

db.col.aggregate([{
    $group:{
        _id:null,
       nested:{field3:{ $avg:"$nested.field3"}}
    }
}])
1 Like

The usage of the field name representation for the computed value in group aggregation cannot be of both these forms, and there are errors as seen below:

"nested.field3": { $avg: "$nested.field3" }
Error: "The field name 'nested.field3' cannot contain '.'"

nested: { field3: { $avg: "$nested.field3" } }
Error: "The field 'nested' must be an accumulator object"

You can work with this as follows, to get the desired result:

db.col.aggregate([
  {
      $group:{
          _id: null,
          nested_field3: { $avg: "$nested.field3" },
          nested_field4: { $avg: "$nested.field4" }
      }
  },
  {
      $project: {
          nested: { field3: "$nested_field3",  field4: "$nested_field4" }
      }
  }
])
1 Like