Anda dapat menggunakan $redact
tahap untuk mencapai ini. Ini menghindari penggunaan $sort
lalu lakukan lagi $group
atau $unwind
.
$group
oleh_id
dan dapatkanmax_num_sold
maksimum untuk setiap grup, kumpulkan semua dokumen dalam grup menggunakan$push
operator.$redact
ke dalam sub dokumen per grup, hanya menyimpan yang memilikimax_num_sold
maximum maksimum dinum_sold
. mereka
kode contoh:
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"]}},
])
data uji:
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"}
])
hasil tes:
{
"_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"
}
]
}