【问题标题】:MongoDB aggregate $lookup to return unmatched items from the main collectionMongoDB 聚合 $lookup 以从主集合中返回不匹配的项目
【发布时间】:2019-04-26 17:14:55
【问题描述】:

我想要来自 USERS 集合的不匹配数据。这里我有两个集合1) USERS2) COMPANY。我可以使用聚合函数从USERS 中获取匹配的数据。但在这种情况下,我想要来自未分配给公司的 USERS 表中的数据。

USERS 表

{
 _id: "AAA",
 fullName:"John Papa"
},
{
_id: "BBB",
fullName:"Robin Son"
}

公司表

{
 _id: "1sd1s",
 Name:"Lumbar Company"
 User:"AAA"
},
{
 _id: "23s1dfs3",
 Name:"Patricia"
 User:"AAA"
}

【问题讨论】:

  • 所以输出应该是{ _id: "BBB", fullName:"Robin Son" }?
  • @AnthonyWinzlet 是的,输出应该是{ _id: "BBB", fullName:"Robin Son" }

标签: mongodb aggregation-framework


【解决方案1】:

$lookup 像 LEFT OUTER JOIN 一样工作,所以当没有匹配时它会删除空数组。然后你可以使用$size 只获取空数组:

db.users.aggregate([
    {
        $lookup: {
            from: "company",
            localField: "_id",
            foreignField: "User",
            as: "companies"
        }
    },
    {
        $match: {
            $expr: {
                $eq: [ { "$size": "$companies" }, 0 ]
            }
        }
    }
])

Mongo Playground

【讨论】:

  • 感谢您的解决方案 :-) 这对我很有帮助。我在$match step、$match: { companies: { $exists: true, $eq: [] } } Mongo Playground 处做了小改动
猜你喜欢
  • 2021-07-28
  • 1970-01-01
  • 2021-02-22
  • 2018-12-10
  • 2014-10-14
  • 1970-01-01
  • 2022-01-05
  • 2019-03-16
  • 1970-01-01
相关资源
最近更新 更多