MongoDB 从结果集中获取交集

MongoDB get intersection from result set

我是 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"]
}

我应该使用聚合来实现吗?请帮我查询一下。

查询

  • 如果 $setIntersection 可以用作累加器,我们可以对它们进行分组和相交,但它不能用作累加器
  • 按城市分组并推送这些数组
  • 减少每个并相交(相同代码的 3 倍)

Playmongo

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"}}}