简体   繁体   中英

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

collection is student which have fields -- _id, student_name, teacher_id, subject_id, book_id

how can I fetch ids from 1, 2, 3 collections simultaneously and insert to corresponding id in collection

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?

can someone please help

Well, in that case, you need to fetch all the documents from those 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.

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.

Hope this will solve your problem:)

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.

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