mongodb - Retrieve only documents with the highest value -
i want write query finds documents highest value. there multiple documents same value, , want of them.
i know can use sort sort high low. don't know how many documents there are. won't work.
{ total: 1, id: 1 }, { total: 1, id: 2 }, { total: 2, id: 3 }, { total: 2, id: 4 }, { total: 3, id: 5 }, { total: 3, id: 6 }
in example want return documents have total 3
. how can query documents have highest value?
this work you:
db.yourcollectionname.aggregate([ { $group:{ _id: null, high_val: {$max:"$total"} } }, { $lookup:{ from: "yourcollectionname", localfield: "high_val", foreignfield: "total", as: "elements" } }, { $unwind: "$elements" }, { $project:{ _id:false, id: "$elements.id", total: "$elements.total" } } ]);
here $lookup used take max value retrieved initial $group, , apply same table retrieve matching records.
i'm there better way this, couldn't resist, i've started using $lookup, exploring can do.
Comments
Post a Comment