3
如果我有這樣一個集合:合併多個團體聚集在MongoDB中
{
"store" : "XYZ",
"total" : 100
},
{
"store" : "XYZ",
"total" : 200
},
{
"store" : "ABC",
"total" : 300
},
{
"store" : "ABC",
"total" : 400
}
我可以聚集拿到訂單的$sum
集合中:
db.invoices.aggregate([{$group: { _id: null, total: { $sum: "$total"}}}])
{
"result": [{
"_id": null,
"total": 1000
}
],
"ok": 1
}
,我可以得到按商店分組的訂單的$sum
:
db.invoices.aggregate([{$group: { _id: "$store", total: { $sum: "$total"}}}])
{
"result": [{
"_id": "ABC",
"total": 700
}, {
"_id": "XYZ",
"total": 300
}
],
"ok": 1
}
但我該如何做到這一點一個查詢?
你真棒,謝謝! – 2015-02-10 03:35:29
只是!順便說一句。像這樣的聚合..只是爲這種多個分組/投影調用2個單獨的調用更有效率? – 2015-02-10 05:04:17
@MattKim - 謝謝。儘管聚合解決方案涉及多個階段,但它比兩次數據庫調用,然後在應用程序代碼中進行一些後處理有效地工作。如果解決方案涉及諸如'$ unwind'等非常昂貴的階段,則情況將會不同。 – BatScream 2015-02-10 05:09:24