gpt4 book ai didi

MongoDB $查找嵌套文档

转载 作者:IT老高 更新时间:2023-10-28 13:07:26 26 4
gpt4 key购买 nike

我是 mongo 的新手,并且在以下方面苦苦挣扎。我有 2 个集合,结构如下。对于我的生活,我无法弄清楚如何对学校收藏进行 $lookup。阅读其他帖子,我肯定使用 ObjectId 作为引用以及外部字段。

下面是我的结构:

校友:

{
"_id": "john",
"items": [
{
"name": "John",
"items": [
{
"school": ObjectId("56de35ab520fc05b2fa3d5e4"),
"grad": true
},
{
"school": ObjectId("56de35ab520fc05b2fa00000"),
"grad": false
}
]
},
{
"name": "Johnny"
// notice no nested items, this doc should still be included in result
},
{
"name": "Jon",
"items": [
{
"school": ObjectId("56de35ab520fc05b2fa11111"),
"grad": false
}
]
}
]
}

学校

{
_id: ObjectId("56de35ab520fc05b2fa3d5e4"),
name: "Some University",
street: "ABC Boulevard"
}

我想要得到什么:

{
"_id": "john",
"items": [
{
"name": "John",
"items": [
{
"school": ObjectId("56de35ab520fc05b2fa3d5e4"),
"grad": true,
"schoolInfo": {
_id: ObjectId("56de35ab520fc05b2fa3d5e4"),
name: "Some University",
street: "ABC Boulevard"
}
},
{
"school": ObjectId("56de35ab520fc05b2fa00000"),
"grad": true,
"schoolInfo": {
_id: ObjectId("56de35ab520fc05b2fa00000"),
name: "Another University",
street: "123 Boulevard"
}
}
]
},
{
name: "Johnny"
},
{
"name": "Jon",
"items": [
{
"school": ObjectId("56de35ab520fc05b2fa11111"),
"grad": true,
"schoolInfo": {
_id: ObjectId("56de35ab520fc05b2fa11111"),
name: "Some University",
street: "ABC Boulevard"
}
}
]
}
]
}

我尝试过的查询无济于事:

db.alumni.aggregate([
{$match: {_id: 'john'}},
{$lookup: {
from: 'schools',
localField: 'items.items.school',
foreignField: '_id',
as: 'schoolInfo'}}
])

任何帮助将不胜感激!

最佳答案

在这种情况下,需要在聚合框架中很好地使用 $unwind 和 $project

请看下面:

db.alumni.aggregate([
{$match: {_id: 'john'}},
{$unwind:"$items"},
{$unwind:"$items.items"},
{$lookup: {
from: 'schools',
localField: 'items.items.school',
foreignField: '_id',
as: 'schoolInfo'}},
{$unwind:"$schoolInfo"},
{$project:{
"_id":1,
"items":[{
"name":"$items.name",
"items":[{
"school":"$schoolInfo._id" ,
"grad":"$items.items.grad" ,
"schoolInfo":"$schoolInfo"
}]
}]
}}
]).pretty()

看看它是如何工作的 - 尝试从查询中删除聚合阶段并检查文档结构。

关于MongoDB $查找嵌套文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36022456/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com