假设我的收藏中有以下文档:
{
"_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})
返回匹配的文档
,但始终包含所有数组项
shapes
:
{ "shapes":
[
{"shape": "square", "color": "blue"},
{"shape": "circle", "color": "red"}
]
}
不过,我想拿到文件
(文件1)
只包含
color=red
:
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
我该怎么做?