如何根据 MongoDB 数组中的子文档过滤父项?

How to filter the parent item based on a sub document within an array in MongoDB?

我们有以下 MongoDb 文档的架构。我只想显示标志 "Display" 设置为 true 的项目。

{
  id: 123,
  properties : [ 
     {name : "Name", value: "Value"},
     {name : "Description", value: "A description of the item"},
     {name : "Display", value: true}
 ]

}

我不知道如何在 MongoDB 中执行此操作。任何帮助将不胜感激。

要匹配完整的数组项,您需要使用 $elemMatch 运算符。

db.col.find({properties : {$elemMatch : {name : "Display", value : true}}});

这样,只会返回包含同时匹配所有条件的数组项的文档。

查询

db.col.find({"properties.name" : "Display", "properties.value" : true});

将匹配数组项中的任意组合。

例如,在这种情况下还会返回以下文档:

{
    id: 123,
    properties : [
        {name : "Name", value: "Value"},
        {name : "Description", value: "A description of the item"},
        {name : "Display", value: false},
        {name : "AnotherOne", value: true}
    ]
}