Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So the output will be

{
  channel: "Xamper",
  unSubscribers: 1
}

Which is similar to the outer excluding join of SQL

enter image description here

like image 655
Ashh Avatar asked Oct 14 '25 16:10

Ashh


1 Answers

You can use below pipeline in 3.6.

$lookup with pipeline to join the Channels collection to Users collection on subscribers

$count with $not $in to compare the subscribers against each id in the Users collection and output the no of matched documents.

$project to project the output fields.

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 ] }
  }}
])
like image 124
s7vr Avatar answered Oct 17 '25 05:10

s7vr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!