0

I have these 2 collections in MongoDb:

User

{
  _id: ObjectId("xxxxxxxxx"),
  roleId: ObjectId: ("xxxxxxxxx)
}

Courses

{
  _id: ObjectId("xxxxxxxxx"),
  name: "Course 1",
  relationRoleCourses: [
    {
      userRoleId: "xxxxxxxxxxx"
    },
    {
      userRoleId: "xxxxxxxxxxx"
    }
  ]
}

I'm looking for a query using lookup to get all users with their corresponding courses where the course must include the role of the user.

Expected Result

{
  _id: ObjectId("xxxxxxxxx"),
  roleId: ObjectId: ("xxxxxxxxx),
  courses: [
    {
      _id: ObjectId("xxxxxxxxx"),
      name: "Course 1",
    },
    {
      _id: ObjectId("xxxxxxxxx"),
      name: "Course 2",
    }
  ],
}

Considerations:

  • In the relationRoleCourses array the userRoleId is a string, not an ObjectId.

1 Answer 1

-1

You can try this:

db.users.aggregate([
  {
    $lookup: {
      from: "courses",
      localField: "roleId",
      foreignField: "relationRoleCourses.userRoleId",
      as: "courses"
    }
  }
])
Sign up to request clarification or add additional context in comments.

2 Comments

Not working, courses are empty in the result
That’s because of string stored roleId, check this mongoplayground.net/p/hL21XKr3F-B and this, it depends also on the mongo version. stackoverflow.com/questions/41093647/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.