Anda dapat menggabungkan seperti di bawah ini:
$group
menurutsubject
danimportance
, dapatkan jumlah masing-masing.- Lalu datanglah bagian yang sulit,
$project
, itu akan tumbuh secara linier sehubungan dengan jumlah opsi yangimportance
lapangan bisa tahan. saat ini tiga -high
,low
danmedium
. $group
hasilnya kembali lagi dengansubject
dan gunakan$sum
operator untukaccumulate
menghitung nilai yang berbeda dari bidang urgensi.
contoh kode:
db.t.aggregate([
{$group:{"_id":{"subject":"$subject",
"importance":"$importance"},
"count":{$sum:1}}},
{$project:{"_id":0,
"subject":"$_id.subject",
"result":{$cond:[
{$eq:["$_id.importance","high"]},
{"high":"$count"},
{$cond:[{$eq:["$_id.importance","low"]},
{"low":"$count"},
{"medium":"$count"}]}]}}},
{$group:{"_id":"$subject",
"low":{$sum:"$result.low"},
"medium":{$sum:"$result.medium"},
"high":{$sum:"$result.high"}}},
])
data uji:
db.t.insert([
{"subject":"history","importance":"high"},
{"subject":"geography","importance":"low"},
{"subject":"history","importance":"low"},
{"subject":"history","importance":"medium"},
{"subject":"geography","importance":"low"},
{"subject":"history","importance":"low"}
])
hasil:
{ "_id" : "geography", "low" : 2, "medium" : 0, "high" : 0 }
{ "_id" : "history", "low" : 2, "medium" : 1, "high" : 1 }