我是 MongoDB 的新手。我有 pymongo 可以訪問 mongodb。
資料是這種格式
{
shop:"shop A",
city:"xxx",
electronics:["phone","laptop","television"],
stationary:["pen","pencil","eraser"],
furniture:["sofa","stool"]
}
{
shop: "shop B",
city:"xxx",
electronics:["camera","radio","phone","television"],
stationary:["pen","pencil","eraser","sharpner"],
furniture:["chair","table","sofa"]
}
...
我想在 xxx 市的所有商店中獲得電子、文具和家具的交集。
期望的輸出:
{
electronics:["phone","television"],
stationary:["pen","pencil","eraser"],
furniture:["sofa"]
}
我應該使用聚合來實作這一點嗎?請幫我查詢。
uj5u.com熱心網友回復:
詢問
- 如果
$setIntersection可以用作累加器,我們可以對它們進行分組和相交,但它不能用作累加器 - 按城市分組并推送這些陣列
- 在每個中減少并相交(其 3 倍相同的代碼)
玩蒙哥
aggregate(
[{"$group":
{"_id": "$city",
"electronics": {"$push": "$electronics"},
"stationary": {"$push": "$stationary"},
"furniture": {"$push": "$furniture"}}},
{"$set":
{"electronics":
{"$reduce":
{"input": "$electronics",
"initialValue": null,
"in":
{"$cond":
[{"$eq": ["$$value", null]}, "$$this",
{"$setIntersection": ["$$value", "$$this"]}]}}},
"stationary":
{"$reduce":
{"input": "$stationary",
"initialValue": null,
"in":
{"$cond":
[{"$eq": ["$$value", null]}, "$$this",
{"$setIntersection": ["$$value", "$$this"]}]}}},
"furniture":
{"$reduce":
{"input": "$furniture",
"initialValue": null,
"in":
{"$cond":
[{"$eq": ["$$value", null]}, "$$this",
{"$setIntersection": ["$$value", "$$this"]}]}}}}}])
編輯
以上是針對所有城市的,要找到那些,如果你只想要一個特定的城市,你可以用這兩個階段替換第一組
{"$match": {"city": {"$eq": "xxx"}}},
{"$group":
{"_id": null,
"electronics": {"$push": "$electronics"},
"stationary": {"$push": "$stationary"},
"furniture": {"$push": "$furniture"}}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474016.html
