您可以使用$redact阶段来实现这一点。它避免了使用$sort然后再次做一个$group or an $unwind.
-
$group
by _id
并得到最大值max_num_sold
对于每个组,使用以下方法累积该组中的所有文档$push操作员。
-
$redact
到每组的子文档中,只保留那些具有最大max_num_sold
在他们的num_sold
示例代码:
db.getCollection('sales').aggregate([
{$group:{"_id":"$hash",
"max_num_sold":{$max:"$num_sold"},
"records":{$push:"$$ROOT"}}},
{$redact:{$cond:[{$eq:[{$ifNull:["$num_sold","$$ROOT.max_num_sold"]},
"$$ROOT.max_num_sold"]},
"$$DESCEND","$$PRUNE"]}},
])
测试数据:
db.getCollection('sales').insert([
{"title":"Foo","hash":17,"num_sold":49,"place":"ABC"},
{"title":"Bar","hash":18,"num_sold":55,"place":"CDF"},
{"title":"Baz","hash":17,"num_sold":55,"place":"JKN"},
{"title":"Spam","hash":17,"num_sold":20,"place":"ZSD"},
{"title":"Eggs","hash":18,"num_sold":20,"place":"ZDF"}
])
测试结果:
{
"_id" : 18,
"max_num_sold" : 55,
"records" : [
{
"_id" : ObjectId("567874f2b506fc2193a22696"),
"title" : "Bar",
"hash" : 18,
"num_sold" : 55,
"place" : "CDF"
}
]
}
{
"_id" : 17,
"max_num_sold" : 55,
"records" : [
{
"_id" : ObjectId("567874f2b506fc2193a22697"),
"title" : "Baz",
"hash" : 17,
"num_sold" : 55,
"place" : "JKN"
}
]
}