假设我的收藏中有以下文件:
{
"_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
中的ALL数组项:
{ "shapes":
[
{"shape": "square", "color": "blue"},
{"shape": "circle", "color": "red"}
]
}
但是,我希望只使用包含color=red
的数组来获取文档文档(1):
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
我该怎么做呢?