MongoDB - 查找多个属性与同一数组元素中的条件匹配的文档

MongoDB - find documents where several properties match condition within the same array element

文件:

{ 
    "_id" : ObjectId("5c4dd63bd76f061ef0dbcf28"), 
    "fruits" : [
        {
            "color" : "red", 
            "name" : "strawberry"
        }, 
        {
            "color" : "green", 
            "name" : "cucumber"
        }
    ]
}

匹配查询:

{ "fruits.name": "strawberry", "fruits.color": "green" }

不使用聚合框架,我如何告诉 MongoDB 仅 return 文档,其中 "fruits" 数组元素之一与查询中的两个条件都匹配(所以在我的如果结果是没有文件)?

您需要使用 $elemMatch 查询运算符来匹配数组中的多个条件

db.collection.find({
  "fruits": {
    "$elemMatch": {
      "name": "strawberry",
      "color": "green"
    }
  }
})