Getting a complete object via $max in mongodb aggregation -
i have collection of objects need grouped masterid or id if masterid absent. of group of objects same masterid need find 1 highest pos attribute ($max: "$pos"). however, struggle complete object pos maximized, seems via aggregation can pos attribute, not whole object. here sample aggregation use, lacking $ifnull masterid:
> db.tst.aggregate([{ "$group": { "_id": "$masterid", "pos": { "$max": "$pos" } } }]) sample objects be:
> db.tst.find() { "_id" : objectid("547d6bd28e47d05a9a492e2e"), "masterid" : "master", "pos" : "453", "id" : "hallo" } { "_id" : objectid("547d6bda8e47d05a9a492e2f"), "masterid" : "master", "pos" : "147", "id" : "welt" } { "_id" : objectid("547d6be68e47d05a9a492e30"), "masterid" : "master2", "pos" : "1", "id" : "welt" } the wanted aggregation result is:
{ "_id" : objectid("547d6bd28e47d05a9a492e2e"), "masterid" : "master", "pos" : "453", "id" : "hallo" } { "_id" : objectid("547d6be68e47d05a9a492e30"), "masterid" : "master2", "pos" : "1", "id" : "welt" } is there way achieve result via aggregation, or need use $push obtain grouped objects , implement maximisation on pos in java code around aggregation?
this question mongodb aggregation: how return object min/max instead of value indicates $first or $last should used on objects sorted pos, fail see how returns whole object.
start sorting pos descending. way, first document encountered each masterid document highest pos. can use $$root refer entire document being processed in pipeline.
db.tst.aggregate([ { "$sort" : { "pos" : -1 } }, { "$group": { "_id": { $ifnull: [ "$masterid", "$_id" ] }, "max_doc" : { "$first" : "$$root" } } } ])
Comments
Post a Comment