[英]how can i agregate datas from different collections in mongodb using nodejs?
I am using mongoDB and nodejs I have 4 collections collection 1 is teacher with fields teacher_id, teacher_name collection 2 is subject with fieldssubject _id, subject_name collection 3 is book with fields book_id, book_name我正在使用 mongoDB 和 nodejs 我有 4 个 collections 集合 1 是教师,字段为teacher_id,teacher_name 集合 2 是主题,字段为 _id,subject_name 集合 3 是书,字段为 book_id,book_name
collection is student which have fields -- _id, student_name, teacher_id, subject_id, book_id集合是具有字段的学生 -- _id、学生姓名、教师 ID、主题 ID、书籍 ID
how can I fetch ids from 1, 2, 3 collections simultaneously and insert to corresponding id in collection如何同时从 1、2、3 collections 获取 id 并插入到集合中的相应 id
I have tried some which always ask for a matching field... is ther any function which returns data from collection even though no match field?我已经尝试过一些总是要求匹配字段的...是否有任何 function 即使没有匹配字段也会从集合中返回数据?
can someone please help有人可以帮忙吗
Well, in that case, you need to fetch all the documents from those collections.那么,在这种情况下,您需要从那些 collections 中获取所有文档。 That will be a bit costly aggregation but I'm adding here in code:这将是一个有点昂贵的聚合,但我在代码中添加:
Firstly, I'm grouping on null, to avoid to attach lookup value to every single document in teacher collection.首先,我在 null 上进行分组,以避免将查找值附加到教师集合中的每个文档。
db.teacher.aggregate([
{
$group:{
"_id":null,
"root":{
$push:"$$ROOT"
}
}
},
{
$lookup:
{
from:"subject",
pipeline: [],
as: "subjectLookup"
}
},
{
$lookup:
{
from:"book",
pipeline: [],
as: "bookLookup"
}
},
{
$lookup:
{
from:"student",
pipeline: [],
as: "studentLookup"
}
}
]).pretty()
These lookups will give the array which contains all the documents from respective collections, you can limit the documents by adding $match
stage in the pipeline of lookup stage.这些查找将给出包含来自各个 collections 的所有文档的数组,您可以通过在查找阶段的管道中添加$match
阶段来限制文档。
Hope this will solve your problem:)希望这能解决你的问题:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.