原始数据:
{"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"}
想获得的数据:
{"title":"Baz", "hash": 17, "num_sold": 55,
"place": "JKN"}
{"title":"Bar", "hash": 18, "num_sold": 55,
"place": "CDF"}
语句如下:
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"]}},
])