mongodb - 仅检索 MongoDB 集合中对象数组中的查询元素

标签 mongodb mongodb-query aggregation-framework projection

假设我的收藏中有以下文档:

{  
   "_id":ObjectId("562e7c594c12942f08fe4192"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"blue"
      },
      {  
         "shape":"circle",
         "color":"red"
      }
   ]
},
{  
   "_id":ObjectId("562e7c594c12942f08fe4193"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"black"
      },
      {  
         "shape":"circle",
         "color":"green"
      }
   ]
}
<小时/>

进行查询:

db.test.find({"shapes.color": "red"}, {"shapes.color": 1})

或者

db.test.find({shapes: {"$elemMatch": {color: "red"}}}, {"shapes.color": 1})
<小时/>

返回匹配的文档(文档 1),但始终包含形状中的所有数组项:

{ "shapes": 
  [
    {"shape": "square", "color": "blue"},
    {"shape": "circle", "color": "red"}
  ] 
}

但是,我只想获取包含 color=red 的数组的文档(文档 1):

{ "shapes": 
  [
    {"shape": "circle", "color": "red"}
  ] 
}

我该怎么做?

最佳答案

MongoDB 2.2 的新功能 $elemMatch投影运算符提供了另一种方法来更改返回的文档,使其仅包含第一个匹配的shapes元素:

db.test.find(
    {"shapes.color": "red"}, 
    {_id: 0, shapes: {$elemMatch: {color: "red"}}});

返回:

{"shapes" : [{"shape": "circle", "color": "red"}]}

在 2.2 中,您还可以使用 $ projection operator 来执行此操作,其中投影对象字段名称中的 $ 表示查询中该字段的第一个匹配数组元素的索引。以下返回与上面相同的结果:

db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});

MongoDB 3.2 更新

从 3.2 版本开始,您可以使用新的 $filter聚合运算符在投影期间过滤数组,其优点是包含所有匹配项,而不仅仅是第一个匹配项。

db.test.aggregate([
    // Get just the docs that contain a shapes element where color is 'red'
    {$match: {'shapes.color': 'red'}},
    {$project: {
        shapes: {$filter: {
            input: '$shapes',
            as: 'shape',
            cond: {$eq: ['$$shape.color', 'red']}
        }},
        _id: 0
    }}
])

结果:

[ 
    {
        "shapes" : [ 
            {
                "shape" : "circle",
                "color" : "red"
            }
        ]
    }
]

关于mongodb - 仅检索 MongoDB 集合中对象数组中的查询元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46110436/

相关文章:

mongodb - 如何从mongodb中的子文档中查找数据

MongoDb 试图对嵌入式文档进行计数

Mongodb 对内部数组进行排序

mongodb - mgo $unwind 聚合结果到未知元素种类 (0x2E)

javascript - express promise 链错误

javascript - 如何通过 Mongoose 中的 $inc 增加值(value)

node.js - 我如何总结我的 mongodb 集合中的值?

java - DDD Java with Spring - Repository 返回 Mono/Flux

mongodb - 如何将两个数组转换为 mongoDB 中的对象,其中第一个数组具有多个相同的值

MongoDB $lookup 不使用索引