简体   繁体   English

使用 $lookup 在 mongodb 中进行外部连接

[英]Outer join in mongodb using $lookup

I have a Channels collection我有一个频道集合

{
  channel: "Xamper",  //unique
  subscribers: [
    ObjectId("5a934e000102030405000000"),
    ObjectId("5a934e000102030405000001"),
    ObjectId("5a934e000102030405000002")
  ]
}

And a Users collection和一个用户集合

{
  _id: ObjectId("5a934e000102030405000000"),
  name: "Bradman"
},
{
  _id: ObjectId("5a934e000102030405000001"),
  name: "Hartin"
},
{
  _id: ObjectId("5a934e000102030405000002"),
  name: "Migra"
},
{
  _id: ObjectId("5a934e000102030405000004"),
  name: "Polycor"
}

Now I need to find with Channel name "Xamper" and count the users which are not in subscribers array现在我需要找到频道名称"Xamper"并计算不在subscribers数组中的subscribers

So the output will be所以输出将是

{
  channel: "Xamper",
  unSubscribers: 1
}

Which is similar to the outer excluding join of SQL类似于 SQL 的外部排除连接

在此处输入图片说明

You can use below pipeline in 3.6.您可以在 3.6 中使用以下管道。

$lookup with pipeline to join the Channels collection to Users collection on subscribers $lookup使用管道将 Channels 集合加入到订阅者的 Users 集合中

$count with $not $in to compare the subscribers against each id in the Users collection and output the no of matched documents. $count$not $in将订阅者与用户集合中的每个 id 进行比较,并输出匹配文档的数量。

$project to project the output fields. $project投影输出字段。

db.Channels.aggregate([
  { "$lookup":  {
    "from": "Users",
    "let": { "subscribers": "$subscribers" },
    "pipeline": [
      { "$match": { "$expr": { "$not": { "$in": [ "$_id", "$$subscribers" ] }}}},
      { "$count": "count" }
    ],
    "as": "lookupresult"
  }},
  { "$project": {
    "channel":  1,
    "unSubscribers": { "$arrayElemAt": [ "$lookupresult.count", 0 ] }
  }}
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM