MongoDB $lookup on nested document

后端 未结 2 1841
暖寄归人
暖寄归人 2020-12-05 10:17

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 sc

2条回答
  •  青春惊慌失措
    2020-12-05 11:06

    Would that handle better the multiple schools in the $items.items array?

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

    I didn't address the case for missing $items.items but you can look at $unwind empty array Additionally, it'd be better to leave an empty array instead of nothing when there's no entry, ie have

    {
        name: "Johnny",
        items: [],
    },
    

提交回复
热议问题