Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Using $group in a $addFields

Is it possible to use a $group - aggregration when adding a field with $addFields to a document?

/* 1 */
{
    "_id" : "1",
    "version" : 0,
    "data" : "aaaa"
}

/* 2 */
{
    "_id" : "2",
    "version" : 0,
    "data" : "aaaa"
}

/* 3 */
{
    "_id" : "3",
    "version" : 1,
    "data" : "aaaa"
}

The aggregation is something similiar to this.

db.getCollection("TestCollection").aggregate([{

$addFields: {
        "test": {
            $group: {
                _id: null,
                    
            }
        }
    }
}])

Hello Hien Nguyen,

It is not possible to add a $group stage to an $addFields stage. They are to used separately. But, you can use the $addFields before a $group stage or / and after.

For example:

db.collection.aggregate( [
  { $addFields: { ... } },
  { $group: { ... } },
  { $addFields: { ... } }
] )

What is it you are trying, in terms of getting a result? May be if you tell what you are expecting to get as output from the aggregation, perhaps I can suggest how to form the query using appropriate stages.

1 Like