【问题标题】:Outer join in mongodb using $lookup使用 $lookup 在 mongodb 中进行外部连接
【发布时间】:2019-02-06 19:34:21
【问题描述】:

我有一个频道收藏

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

还有一个用户集合

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

现在我需要找到频道名称"Xamper"并计算不在subscribers数组中的用户

所以输出将是

{
  channel: "Xamper",
  unSubscribers: 1
}

类似于SQL的外排除连接

【问题讨论】:

  • 您是否尝试过在查找管道中使用$not $in 来获取订阅者数组中不存在的所有用户文档?
  • 是的,这就是答案...我刚刚找到...请将其作为答案发布...

标签: javascript node.js mongodb mongoose aggregation-framework


【解决方案1】:

您可以在 3.6 中使用以下管道。

$lookup 使用管道将 Channels 集合加入订阅者的 Users 集合

$count 和 $not $in 将订阅者与用户集合中的每个 id 进行比较,并输出匹配文档的数量。

$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 ] }
  }}
])

【讨论】:

    猜你喜欢
    • 2016-11-14
    • 1970-01-01
    • 2019-06-20
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    相关资源
    最近更新 更多