Robo 3T: Want to fetch data with project from multiple Collections?

I want to fetch a list of organizations that are in the ABC project.
There are two different collections i.e. Organizations & Projects in which project_id is common in both collections. and I don’t know the project_id and I know the only project_name i.e. ABC and want to get data by using this project_name {present in Projects collection} ???

Hi @Saloni_Salodia,

You can use a $lookup stage in an Aggregation Pipeline to include all related Organizations to a Project based on the common field (project_id) as follows:

// SETUP
db.projects.createIndex({ project_name: 1 });
// newly inserted document will have an _id field automatically generated
db.projects.insert({ project_name: "ABC" })

db.organizations.createIndex({ project_id: 1 });
// associate the _id value from the Projects collection as the project_id field for the Organizations
db.organizations.insert({ project_id: db.projects.findOne()._id, organization_name: "Some Organization" })
db.organizations.insert({ project_id: db.projects.findOne()._id, organization_name: "Some Other Organization" })
// PIPELINE
db.projects.aggregate([
{ $match: { project_name: "ABC" } },
{ $lookup: {
  from: "organizations",
  localField: "_id",
  foreignField: "project_id",
  as: "organizations"
}},
]);
2 Likes

Hi @alexbevi,
I got your solution working…!

Thank you…! :blush:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.