在mongodb中使用$或嵌套的对象数组

时间:2018-05-23 11:17:10

标签: json mongodb mongodb-query aggregation-framework pymongo

我有以下收藏

[
  {"overlaps": [{"BB1": "itemA", "iou": 0.1,  "BB2": "itemB"},{"BB1": "itemB", "iou": 0.4,  "BB2": "itemC"}], "City": "Paris", "mode": "RGB","path": "photo1.png"},
  {"overlaps": [{"BB1": "itemA", "iou": 0.5,  "BB2": "itemC"}], "City": "London", "mode": "RGB","path": "photo2.png"},
  {"overlaps": [{"BB1": "itemB", "iou": 0.8,  "BB2": "itemB"}], "City": "London", "mode": "greyscale","path": "photo3.png"},
  {"overlaps": [{"BB1": "itemA", "iou": 0.2,  "BB2": "itemC"},{"BB1": "itemA", "iou": 0.8,  "BB2": "itemC"}], "City": "Berlin", "mode": "RGB","path": "photo4.png"},
  {"overlaps": [{"BB1": "itemA", "iou": 0.9,  "BB2": "itemB"}], "City": "NY", "mode": "greyscale","path": "photo5.png"},
  {"overlaps": [{"BB1": "itemA", "iou": 0.8,  "BB2": "itemB"}], "City": "Roma", "mode": "RGB","path": "photo6.png"}
]

我想检索

的文件
  • 有city = berlin

  • 或者有mode = greyscale

  • OR计算“BB1”:“itemA”和“BB2”之间至少有一个重叠:“itemC”

前两个条件很简单:

cursor = record1.find({"$or": [{"City":"Berlin"},{"mode":"greyscale"}]}) 

如何在查询中添加第三个条件?

1 个答案:

答案 0 :(得分:1)

您应该应用$elemMatch $or条件来获取结果

db.collection.find({
  $or: [{ City: "Berlin" }, { mode: "greyscale" },
    {
      overlaps: {
        $elemMatch: {
          $or: [
            {
              BB1: "itemA",
              BB2: "itemC"
            }
          ]
        }
      }
    }
  ]
})