我的資料如下所示:
{ fname: "bob", age: 33, description: "brown eyes"}
{ fname: "sally", age: 20, description: "tall"}
{ fname: "jim", age: 48 }
我試圖在一個查詢中獲得如下所示的結果:
{
hasDescription: ["bob", "sally"],
noDescription: ["jim"]
}
我一直在玩$bucketAuto這樣的東西:
{
groupBy: { "$cond": [{ "$eq": [ "description", null ] }, true, false ] },
buckets: 2,
}
但我沒有任何成功。任何指導將不勝感激!
uj5u.com熱心網友回復:
詢問
- 組上帶有運算式的組,創建 2 個組,一個有描述,一個沒有(而不是創建組的欄位,我們根據條件創建 2 個組)
- 其他 3 個階段是將結構修復為預期輸出
*我認為您不需要存盤桶,存盤桶用于值范圍
*也可以使用波紋管方面,但方面就像每個欄位運行聚合 1 次,因此速度較慢
Playmongo(滑鼠移動到每個階段的末尾 => 查看in/out每個階段)
aggregate(
[{"$group":
{"_id":
{"$cond":
[{"$ne": [{"$type": "$description"}, "missing"]}, "hasDescription",
"noDescription"]},
"names": {"$push": "$fname"}}},
{"$replaceRoot":
{"newRoot":
{"$cond":
[{"$eq": ["$_id", "noDescription"]}, {"noDescription": "$names"},
{"hasDescription": "$names"}]}}},
{"$group": {"_id": null, "docs": {"$mergeObjects": "$$ROOT"}}},
{"$replaceRoot": {"newRoot": "$docs"}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462443.html
標籤:mongodb
下一篇:在某些條件之前和之后匹配元素
