提问人:pope 提问时间:11/9/2022 最后编辑:J.F.pope 更新时间:11/9/2022 访问量:48
在对象数组 mongodb 中获取二级嵌套对象
Getting second level nested object inside array of objects mongodb
问:
我的数据库如下所示:
[
{
"title": "man",
"articlesType": [
{
"title": "shoes",
"articles": [
{
"title": "shoes1",
"id": "randomId"
},
{
"title": "shoes2",
"id": "alsoRandomId"
}
]
}
]
},
{
"title": "woman",
"articlesType": [
{
"title": "pants",
"articles": [
{
"title": "pants1",
"id": "anotherRandomId"
},
{
"title": "pants1",
"id": "justId"
}
]
}
]
}
]
我期望这样的事情:,是否可以仅使用 ID 来获取此嵌套中的整个对象?
{
"title": "shoes2",
"id": "alsoRandomId"
}
我找到了这个,但对我不起作用
答:
0赞
J.F.
11/9/2022
#1
您可以尝试使用 double 的聚合管道来解构数组两次,然后按所需的过滤(我假设您想按 id 进行匹配)。$unwind
id
最后一步,是以与你想要的相同的方式输出结果。$project
db.collection.aggregate([
{
"$unwind": "$articlesType"
},
{
"$unwind": "$articlesType.articles"
},
{
"$match": {
"articlesType.articles.id": "alsoRandomId"
}
},
{
"$project": {
"title": "$articlesType.articles.title",
"id": "$articlesType.articles.id"
}
}
])
此处的示例
评论