如果 Mongo $lookup 是左外连接,那么它怎么会排除不匹配的文档呢? [英] If Mongo $lookup is a left outer join, then how come it excludes non-matching documents?

查看:29
本文介绍了如果 Mongo $lookup 是左外连接,那么它怎么会排除不匹配的文档呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了一切.如果一个文档根据它的匹配字段没有产生任何匹配的外部文档,那么它为什么不包含在管道的结果集中呢?

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 pipeline's result set?

我正在测试 Mongo 3.2 中的新聚合器,并且我已经通过首先展开然后将文档分组备份来执行嵌套数组查找.我剩下的就是让结果包括所有不符合 $lookup 标准的本地文档,这就是我认为的左外连接"的标准定义.

I'm testing out the new aggregators in Mongo 3.2 and I've gone so far as to perform a nested array lookup by first unwinding, and then grouping the documents back up. All I have left is to have the results include all local documents that didn't meet the $lookup criteria, which is what I thought was the standard definition of "left outer join".

这是查询:

db.users.aggregate([
    {
        $unwind: "$profile",
        $unwind: "$profile.universities"
    },
    {
        $lookup: {
            from: "universities",
            localField: "profile.universities._id",
            foreignField: "_id",
            as: "profile.universities"
        }
    },
    {
        $group: {
            _id: "$_id",
            universities: {
                $addToSet: "$profile.universities"
            }
        }
    }
]).pretty()

所以如果我有一个 user 有一个空的 profile.universities 数组,那么我需要将它包含在结果集中,而不管 $查找 返回任何匹配,但它没有.我该如何做到这一点,以及 Mongo 构造 $lookup 以这种方式操作的任何原因?

So if I have a user that has an empty profile.universities array, then I need it to be included in the result set regardless of the $lookup returning any matches, but it does not. How can I do this, and any reason why Mongo constructed $lookup to operate this way?

推荐答案

此行为与 $lookup 无关,这是因为 $unwind 是省略引用字段缺失的文档或一个空数组.

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.

要在 profile.universities 为空数组时保留展开的文档,可以将其 preserveNullAndEmptyArrays 选项设置为 true:p>

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()

这篇关于如果 Mongo $lookup 是左外连接,那么它怎么会排除不匹配的文档呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆