假设您在我的集合中有以下文档:
{
"_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
中的所有数组项。{ "shapes":
[
{"shape": "square", "color": "blue"},
{"shape": "circle", "color": "red"}
]
}
然而,我想要获取包含color=red
的数组中的文档(文档1):
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
我该如何做这件事?
db.test.find({}, {shapes: {$elemMatch: {color: "red"}}});
- Paul