If Mongo $lookup is a left outer join, then how come it excludes non-matching documents?

后端 未结 1 1323
南旧
南旧 2020-12-30 01:32

The title says it all. How come if a document does not result in any matching outer document according to its matching field, then how come it\'s not included in the pipelin

相关标签:
1条回答
  • 2020-12-30 02:18

    This behavior isn't related to $lookup, it's because the default behavior for $unwind is to omit documents where the referenced field is missing or an empty array.

    To preserve the unwound documents even when profile.universities is an empty array, you can set its preserveNullAndEmptyArrays option to true:

    db.users.aggregate([
        {
            $unwind: "$profile",
            $unwind: {
                path: "$profile.universities",
                preserveNullAndEmptyArrays: true
            }
        },
        {
            $lookup: {
                from: "universities",
                localField: "profile.universities._id",
                foreignField: "_id",
                as: "profile.universities"
            }
        },
        {
            $group: {
                _id: "$_id",
                universities: {
                    $addToSet: "$profile.universities"
                }
            }
        }
    ]).pretty()
    
    0 讨论(0)
提交回复
热议问题