【发布时间】:2018-04-13 16:16:37
【问题描述】:
假设我的收藏中有以下文档:
{
"_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 的数组来获取文档 (Document 1):
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
我该怎么做?
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework projection