假设你在我的Collection 中有以下文件:

{  
   "_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})

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

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

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

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

我该怎么做?

推荐答案

MongoDB 2.2新的$elemMatch投影操作符提供了另一种方法来更改返回的文档,使其仅包含first个匹配的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 Update

从3.2版本开始,可以使用新的$filter聚合操作符在投影期间过滤数组,这样做的好处是包含all个匹配项,而不仅仅是第一个匹配项.

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聚合匹配字符串字符

在MongoDB查询中添加来自另一个集合的匹配文档的计数

Mongoose 排除数组中包含特定嵌套对象的文档

如何为具有相同名称的嵌套字段创建文本索引

MongoDB 使用 pymongo 收集 500K 文档的写入速度很差

在运算符 $map 中嵌入运算符 $exists

Mongodb聚合查找连接两个对象字段的集合数组匹配对象索引字段的总和

mongodb中集合的最大大小是多少

在mongo聚合中将ObjectID转换为字符串

如何在 MongoDb 中进行类似于嵌套 Sql Select 查询的嵌套查询

oplog 在独立 mongod 上启用,不适用于副本集

MongoDB获取聚合查询的executionStats

MongoDB 中 cursor.count() 和 cursor.size() 之间的区别

从命令行创建 MongoDB 用户

如何使用 MongoDB 建模 likes投票系统

从每个组中 Select 前 N 行

如何使用 MongoDB Compass 对数据进行排序

Cannot connect to MongoDB errno:61

按 id 删除记录?

即使重新安装后,Mongo 仍在等待 27017