I saw other examples but still can't get how to do a query using multiple collections in MongoDB. For example, I have two collections, student and wand. Each student has a wand, and each wand has a code. Suppose I want to print all the wands of all the students who are from the house 'Slytherin'. How should I do it?
Asked
Active
Viewed 37 times
0
-
You probably want to look at aggregation pipelines and the `$lookup` operator you can use in there: https://stackoverflow.com/a/33511166/14955 – Thilo Jul 10 '20 at 09:07
-
I tried this db.wand.aggregate([ {$match: {house: 'slytherin'}}, { $lookup:{ from:"student", localField:"wandID", foreignField:"wandID", as:"slytherin1" } }); – Tomoko Jul 10 '20 at 09:35
-
but it doesnt work – Tomoko Jul 10 '20 at 09:35
1 Answers
0
when create the model, use the student _id as a foreign key in the wand model like this
let wand_schema = new Schema({ student_id : ObjectId, code : String, name : String});
module.exports = mongoose.model('wands', wand_schema);
the query.
let filter = { $match : {house : slytherin } }
let lookup = { $lookup : {
from : "wands",
localField : _id,
foreignField : student_id,
as : "wands"
}}
let student_wands = await student_model.aggregate([ filter, lookup ]);
the results will contain a field called wands which is an array of wands from the wands collection