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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.