我在聚合管道的第一階段有這個結果陣列,使用$match:
[
{ a: 1, b: 2 },
{ a: 3, b: 4 }
]
現在我想總結所有的 A 和 B 并且仍然有它們,所以我會得到這樣的結果:
{
total_sum: 10,
items: [...] // first and second objects ofcourse
}
我嘗試過$group,$push但是,push 只從物件中推送特定欄位,我需要命名 A 和 B,而不是只決議所有欄位。
我該怎么做?
uj5u.com熱心網友回復:
$set- 創建新欄位total以求a和b。$group- Group bynull, 表示對所有的求和total并將檔案添加到items陣列中。
使用$$ROOT它將添加整個檔案。
items: {
$push: "$ROOT"
}
如果您只需要一些欄位,請指定(所需的)檔案模式。
items: {
$push: {
A: "$a",
B: "$b"
}
}
$unset(如果使用$push $$ROOT) -total從欄位中洗掉欄位items。
db.collection.aggregate([
{
$set: {
total: {
$sum: [
"$a",
"$b"
]
}
}
},
{
$group: {
_id: null,
total_sum: {
$sum: "$total"
},
items: {
$push: "$$ROOT"
}
}
},
{
$unset: "items.total"
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/467811.html
下一篇:ShardCluster中的ReplicaSet是只存盤“ShardedCopy”還是“AllSharded”Copies?
