Home > Back-end >  How to return another collection's data with any other collection queried?
How to return another collection's data with any other collection queried?

Time:05-24

I have implemented two collections in mongo User and Trainer.

User collection contains id, name, email, and description. and Trainer contains id, coursesMade, and trainerId. here trainerId is the id from the User collection example :

//User collection
{
  id:123,
  name: "alice",
  email: "[email protected]",
  description: "some text"
}

//Trainer collection
{
  id:134,
  coursesMade: 3,
  trainerId: 123
}

now I have some function that gives me a list of trainers. I want to have a query that returns me trainer collection as well as the user reference of that trainerId.

expected output:

{
  id:134,
  coursesMade: 3,
  trainerId: 123,
  trainerDetails: {
    id: 123,
    name: "alice",
    email: "[email protected]",
    description: "some text"
  }
}

I have no idea how to implement this in mongo as a beginner, any general idea would be appreciated.

CodePudding user response:

You need to use lookup

db.trainer.aggregate([
  {
    "$lookup": {
      "from": "user",
      "localField": "trainerId",
      "foreignField": "id",
      "as": "trainers"
    }
  }
])

playground

  • Related