Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb: nested field in $group's _id

Tags:

mongodb

Assume we have documents like this in the collection

{
    _id: {
        element_id: '12345',
        name: 'foobar'
    },
    value: {
        count: 1
    }
}

I am using the aggregation framework to do a $group, like so

db.collection.aggregate([
    { $group: { _id: '$_id.element_id', total: { $sum: '$value.count' } } }
])

And got a result of

{ "result" : [ { "_id" : null, "total" : 1 } ], "ok" : 1 }

Notice that the _id field in the result is null. From experimentation it seems that $group is not allowing a nested field declaration for its _id (e.g. $_id.element_id).

Why is this? And is there a workaround for it?

Thank you.

like image 855
airportyh Avatar asked Dec 07 '22 11:12

airportyh


1 Answers

I found a workaround using $project.

db.collection.aggregate([
    { $project: { element_id: '$_id.element_id', count: '$value.count' } },
    { $group: { _id: '$element_id', total: { $sum: '$count' } } }
])

$project Reshapes a document stream by renaming, adding, or removing fields.

http://docs.mongodb.org/manual/reference/aggregation/#_S_project

like image 117
airportyh Avatar answered Jan 05 '23 03:01

airportyh