Reputation: 424
Input:
[{"gradeName":1,"sectionName":"a","maximumStudents":12},{"gradeName":2,"sectionName":"b","maximumStudents":13}]
In mongodb how to get the _id of gradeName and sectionName from two collection and store in the third collection say mergeddetails
mergeddetails:
[{"grade_id":"60f819e04a9d43158cabad55","section_id":"60f819e04a9d43158cabad54","maximumStudents":12},{"grade_id":"60f819e04a9d43158cabad59","section_id":"60f819e04a9d43158cabad5b","maximumStudents":13}]
where grade_id is the _id of corresponding gradeName,section_id is the _id of corresponding sectionName please help with with mongodb quire i am using nodejs to write the API
Upvotes: 0
Views: 20
Reputation: 3910
You need to use $lookup
for both the collections
db.student.aggregate([
{ $lookup:
{ from: "grade",
localField: "gradeName",
foreignField: "grade",
as: "grade"
}
},
{$lookup:
{ from: "section",
localField: "sectionName",
foreignField: "section",
as: "section"
}
},
{ $unwind: "$grade" },
{ $unwind: "$section" },
{$project:
{
_id:0,
"grade_id":"$grade._id",
"section_id":"$section._id",
maxStudent:1
}
}
])
Upvotes: 1