仅检索 MongoDB 集合中对象数组中的查询元素 [英] Retrieve only the queried element in an object array in MongoDB collection
问题描述
假设您在我的收藏中有以下文档:
Suppose you have the following documents in my collection:
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"shapes":[
{
"shape":"square",
"color":"blue"
},
{
"shape":"circle",
"color":"red"
}
]
},
{
"_id":ObjectId("562e7c594c12942f08fe4193"),
"shapes":[
{
"shape":"square",
"color":"black"
},
{
"shape":"circle",
"color":"green"
}
]
}
<小时>
进行查询:
Do query:
db.test.find({"shapes.color": "red"}, {"shapes.color": 1})
或
db.test.find({shapes: {"$elemMatch": {color: "red"}}}, {"shapes.color": 1})
<小时>
返回匹配的文档 (Document 1),但总是包含 shapes
中的所有数组项:
Returns matched document (Document 1), but always with ALL array items in shapes
:
{ "shapes":
[
{"shape": "square", "color": "blue"},
{"shape": "circle", "color": "red"}
]
}
但是,我只想使用包含 color=red
的数组获取文档 (Document 1):
However, I'd like to get the document (Document 1) only with the array that contains color=red
:
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
我该怎么做?
推荐答案
MongoDB 2.2 的新 $elemMatch
投影运算符提供了另一种方法来改变返回的文档以仅包含 first 匹配的 shapes
元素:
MongoDB 2.2's new $elemMatch
projection operator provides another way to alter the returned document to contain only the first matched shapes
element:
db.test.find(
{"shapes.color": "red"},
{_id: 0, shapes: {$elemMatch: {color: "red"}}});
返回:
{"shapes" : [{"shape": "circle", "color": "red"}]}
在 2.2 中,您也可以使用 $ 投影运算符
,其中投影对象字段名称中的 $
表示该字段的第一个匹配数组元素的索引.以下返回与上述相同的结果:
In 2.2 you can also do this using the $ projection operator
, where the $
in a projection object field name represents the index of the field's first matching array element from the query. The following returns the same results as above:
db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});
MongoDB 3.2 更新
从 3.2 版本开始,您可以使用新的 $filter
聚合运算符用于在投影期间过滤数组,其好处是包括所有匹配项,而不仅仅是第一个.
Starting with the 3.2 release, you can use the new $filter
aggregation operator to filter an array during projection, which has the benefit of including all matches, instead of just the first one.
db.test.aggregate([
// Get just the docs that contain a shapes element where color is 'red'
{$match: {'shapes.color': 'red'}},
{$project: {
shapes: {$filter: {
input: '$shapes',
as: 'shape',
cond: {$eq: ['$$shape.color', 'red']}
}},
_id: 0
}}
])
结果:
[
{
"shapes" : [
{
"shape" : "circle",
"color" : "red"
}
]
}
]
这篇关于仅检索 MongoDB 集合中对象数组中的查询元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!