MongoDB - Get id of the maximum value in a group by query -


i have collection documents below. "_id" or entire document of maximum revision in each group grouped "name".

{     "_id" : objectid("55aa088a58f2a8f2bd2a3793"),     "name" : "abc",     "revision" : 1 }  {     "_id" : objectid("55aa088a58f2a8f2bd2a3794"),     "name" : "abc",     "revision" : 2 }  {     "_id" : objectid("55aa088a58f2a8f2bd2a3795"),     "name" : "def",     "revision" : 1 }  {     "_id" : objectid("55aa088a58f2a8f2bd2a3796"),     "name" : "def",     "revision" : 2 } 

in case, i'd select 2nd , 4th documents. tried various approach including aggregation framework couldn't purely in mongodb query.

is there solution this?

thank you.

try following aggregation pipeline first sorts documents revision field descending , $group name field, add field gets full document using $first operator on $$root system variable expression:

db.collection.aggregate([     {         "$sort": {             "revision": -1         }     },     {         "$group": {             "_id": "$name",             "max_revision": {                 "$max": "$revision"             },             "doc": {                 "$first": "$$root"             }         }     } ]) 

output:

/* 0 */ {     "result" : [          {             "_id" : "def",             "max_revision" : 2,             "doc" : {                 "_id" : objectid("55aa088a58f2a8f2bd2a3796"),                 "name" : "def",                 "revision" : 2             }         },          {             "_id" : "abc",             "max_revision" : 2,             "doc" : {                 "_id" : objectid("55aa088a58f2a8f2bd2a3794"),                 "name" : "abc",                 "revision" : 2             }         }     ],     "ok" : 1 } 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -