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})
返回匹配的文档的(文献1)的,但总是在所有数组项形状
:
Returns matched document (Document 1), but always with ALL array items in shapes
:
{ "shapes":
[
{"shape": "square", "color": "blue"},
{"shape": "circle", "color": "red"}
]
}
不过,我想获得该文件的(文献1)的只包含数组的color = red
:
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
我怎样才能做到这一点?
How can I do this?
推荐答案
MongoDB的2.2新 $ elemMatch
投影算提供了另一种方式来改变返回的文件只包含的第一个的匹配形状
元素:
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,你也可以做到这一点使用 $投影算
,其中 $
在投影对象的字段名称重新presents领域的第一个匹配的数组元素的索引从查询。下面返回与上述相同的结果:
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版本开始,你可以使用新的<一个href=\"https://docs.mongodb.org/master/reference/operator/aggregation/filter/#exp._S_filter\"><$c$c>$filter$c$c>集结算子过滤投影过程中的阵列,它具有包括受益的所有的匹配,而不只是第一个。
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屋!