You Know Who
You Know Who

Reputation: 105

$lookup to an array in MongoDB

I have two collections. USERS

{
  "_id" : "myid",
  "createdAt" : ISODate("2020-12-26T14:00:11.624Z"),
  "email" : "testing@gmail.com"
}

GROUPS

{
  "_id" : "myidgroup",
  "createdAt" : ISODate("2020-12-26T14:00:11.624Z"),
  "name" : "student"
  "userIds": ["myUserId1", "myUserId2"]
}

I want to do a $lookup to the groups collection to get all users with groups

|      email          |     groups.      |
|---------------------|------------------|
|  testing@gmail.com  |   student        |

I expected output like this:

[
  {
     _id: "myUserId"
    email: "testing@gmail.com",
    groups: [
              { 
                "_id": "myGroupId",
                "name": "student"
              }
            ]

  }
]

I know we can do it with new $lookup in mongodb 3.6 and above but I am using mongodb 3.4.

Any help is greatly appreciated.

Upvotes: 1

Views: 45

Answers (1)

turivishal
turivishal

Reputation: 36144

  • $lookup join with groups collection, pass _id as localField and pass userIds as foreignField
  • $project to show required fields
db.users.aggregate([
  {
    "$lookup": {
      "from": "groups",
      "localField": "_id",
      "foreignField": "userIds",
      "as": "groups"
    }
  },
  {
    $project: {
      _id: 1,
      email: 1,
      "groups._id": 1,
      "groups.name": 1
    }
  }
])

Playground

Upvotes: 1

Related Questions