DevWannabe
DevWannabe

Reputation: 117

MongoDB $in with subquery

I have this set of collection below..

teams collection:

{
   total: 3
   data: [
      {
         "_id": "t1",
         "name": "white horse",
         "leader_id": "L1"
         "teamScore": 12,
         "active": 1
      },
      {
         "_id": "t2",
         "name": "green hornets",
         "leader_id": "L2",
         "teamScore": 9,
         "active": 1
      },
      {
         "_id": "t3",
         "name": "pink flaminggo",
         "leader_id": "L3",
         "teamScore": 22,
         "active": 1
      },
   ]
}

leaders collection:

{
   total: 3
   data: [
      {
         "_id": "L1",
         "name": "John Doe",
         "organization": "Software Development",
         "active": 1
      },
      {
         "_id": "L2",
         "name": "Peter Piper",
         "organization": "Software Development"
         "active": 1
      },
      {
         "_id": "L3",
         "name": "Mary Lamb",
         "organization": "Accounting Department"
         "active": 1
      },
   ]
}

The query should look like this: SELECT * FROM teams WHERE active = 1 AND leader_id IN (SELECT id FROM leaders WHERE organization = 'Software Development')

I am new to mongodb and my question is how can the query above be converted in mongoDB aggregation framework?

Upvotes: 3

Views: 2401

Answers (1)

turivishal
turivishal

Reputation: 36104

You can use $lookup with pipeline,

  • $match will check active status
  • $lookup will join leaders collection
    • $match to check leader_id and organization
  • $match check leaders is not [] empty
  • $project to remove leaders field
db.teams.aggregate([
  { $match: { active: 1 } },
  {
    $lookup: {
      from: "leaders",
      let: { leader_id: "$leader_id" },
      as: "leaders",
      pipeline: [
        {
          $match: {
            $and: [
              { $expr: { $eq: ["$_id", "$$leader_id"] } },
              { organization: "Software Development" }
            ]
          }
        }
      ]
    }
  },
  { $match: { leaders: { $ne: [] } } },
  { $project: { leaders: 0 } }
])

Playground

Upvotes: 3

Related Questions