1

I have two collections. USERS

{
  "_id" : "myid",
  "createdAt" : ISODate("2020-12-26T14:00:11.624Z"),
  "email" : "[email protected]"
}

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.      |
|---------------------|------------------|
|  [email protected]  |   student        |

I expected output like this:

[
  {
     _id: "myUserId"
    email: "[email protected]",
    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.

2
  • what have you tried?, can you add your tries in your question. Commented Dec 26, 2020 at 15:35
  • I am using $match to get users, but I have no idea when I $lookup to the groups of users because in the groups userIds is an array Commented Dec 26, 2020 at 15:40

1 Answer 1

1
  • $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

Sign up to request clarification or add additional context in comments.

1 Comment

have no idea that $lookup can do this with different type of data, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.