简体   繁体   English

MongoDB 查询使用不同的 collections?

[英]MongoDB query using different collections?

I saw other examples but still can't get how to do a query using multiple collections in MongoDB.我看到了其他示例,但仍然无法了解如何在 MongoDB 中使用多个 collections 进行查询。 For example, I have two collections, student and wand.例如,我有两个 collections,学生和魔杖。 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当创建 model 时,像这样在魔杖 model 中使用学生 _id 作为外键

    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结果将包含一个名为 wands 的字段,它是 wands 集合中的一个魔杖数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM