[英]MongoDB query for nested array of specific object
I am a new mongodb user, this why I am asking this question.我是 mongodb 的新用户,这就是我问这个问题的原因。 I have a document, in this document I have 3 objects under one _id.我有一份文件,在这份文件中,我在一个 _id 下有 3 个对象。
When I am filtering { "people.age": { $in: [24] } }
I am getting full this document.当我过滤{ "people.age": { $in: [24] } }
时,我正在获取完整的文档。 But I want to see only the matching object. Like for age 24, I just want to see object 2, not object 0 and 1.但我只想看到匹配的 object。比如 24 岁,我只想看到 object 2,而不是 object 0 和 1。
Is it possible to show only the matching object?是否可以只显示匹配的 object? If you kindly explain me it will be helpful for me.如果你好心解释我这将对我有所帮助。
Use $
for projection.使用$
进行投影。
Query 1查询 1
db.collection.find({
"people.age": {
$in: [
24
]
}
},
{
"people.$": 1
})
Sample Mongo Playground (Query 1)示例 Mongo 游乐场(查询 1)
If you just to search people by certain age, you may use the below query as well:如果您只是按特定年龄搜索人,您也可以使用以下查询:
Query 2查询 2
db.collection.find({
"people.age": 24
},
{
"people.$": 1
})
Sample Mongo Playground (Query 2)示例 Mongo 游乐场(查询 2)
Note: $
will returns only the first element of the array.注意: $
将只返回数组的第一个元素。
You may look for aggregation query as:您可以将聚合查询查找为:
$match
- Filter the document by age
. $match
- 按age
过滤文档。$project
- Decorate output documents. $project
- 装饰 output 个文档。 With $filter
operator to filter the document in people
array.使用$filter
运算符过滤people
数组中的文档。db.collection.aggregate([
{
$match: {
"people.age": 24
}
},
{
$project: {
"people": {
$filter: {
input: "$people",
cond: {
$eq: [
"$$this.age",
24
]
}
}
}
}
}
])
Sample Mongo Playground (Aggregation pipeline)示例 Mongo 游乐场(聚合管道)
Reference参考
Project Specific Array Elements in the Returned Array 返回数组中的项目特定数组元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.