需求
在mongodb的集合里有以下这些document:
{
"_id":ObjectId("xxxxx"),
"shapes":[
{ "shape":"square","color":"blue"},
{ "shape":"circle","color":"red"}
]
},
{
"_id":ObjectId("xxxx"),
"shapes":[
{ "shape":"square","color":"black"},
{ "shape":"circle","color":"green"}
]
}
现在查询shapes.clore为red,希望返回:
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
而不是返回整个shapes文档。
解决方案
$操作符
mongodb 2.2也可以使用$操作符:
db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});
$elemMatch
mongodb 2.2可以使用$elemMatch操作符,它只会返回数组里匹配到的第一个元素:
db.test.find(
{"shapes.color": "red"},
{_id: 0, shapes: {$elemMatch: {color: "red"}}});
$filter
Mongodb3.2开始可以使用$filter对数组进行过滤:
db.test.aggregate([
{$match: {'shapes.color': 'red'}},
{$project: {
shapes: {$filter: {
input: '$shapes',
as: 'shape',
cond: {$eq: ['$$shape.color', 'red']}
}},
_id: 0
}}
])