问题描述
我是 mongo 的新手,正在努力解决以下问题.我有 2 个集合,结构如下.对于我的生活,我无法弄清楚如何对学校收藏进行 $lookup .阅读其他帖子,我肯定使用 ObjectId 作为参考以及外国字段.
I'm new to mongo and struggling mightily with the following. I have 2 collections structured as below. For the life of me, I can't figure out how to do a $lookup on the school collection. Reading other posts, I'm definitely using ObjectId for the reference as well as the foreign field.
以下是我的结构:
校友:
{
"_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"
}
}
]
}
]
}
我尝试过的查询无济于事:
The query I've tried to no avail:
db.alumni.aggregate([
{$match: {_id: 'john'}},
{$lookup: {
from: 'schools',
localField: 'items.items.school',
foreignField: '_id',
as: 'schoolInfo'}}
])
任何帮助将不胜感激!
推荐答案
在这种情况下,需要在聚合框架中很好地使用 $unwind 和 $project
in this case there is required a nice play with $unwind and $project in aggregation framework
请看下面:
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()
看看它是如何工作的 - 尝试从查询中删除聚合阶段并检查文档结构.
to see how it works - try removing aggregation stages from query and check document structure.
这篇关于MongoDB $lookup 嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!