简体   繁体   中英

get _id based on value from a collection for a array and insert in mongodb collection

Input:

[{"gradeName":1,"sectionName":"a","maximumStudents":12},{"gradeName":2,"sectionName":"b","maximumStudents":13}]

In mongodb how to get the _id of gradeName and sectionName from two collection and store in the third collection say mergeddetails

mergeddetails:

[{"grade_id":"60f819e04a9d43158cabad55","section_id":"60f819e04a9d43158cabad54","maximumStudents":12},{"grade_id":"60f819e04a9d43158cabad59","section_id":"60f819e04a9d43158cabad5b","maximumStudents":13}]

where grade_id is the _id of corresponding gradeName,section_id is the _id of corresponding sectionName please help with with mongodb quire i am using nodejs to write the API

You need to use $lookup for both the collections

db.student.aggregate([
  { $lookup: 
    { from: "grade", 
      localField: "gradeName", 
      foreignField: "grade", 
      as: "grade" 
    } 
  }, 
  {$lookup: 
    { from: "section", 
      localField: "sectionName", 
      foreignField: "section", 
      as: "section" 
    }
  },
  { $unwind: "$grade" },
  { $unwind: "$section" }, 
  {$project:
    {
      _id:0,
      "grade_id":"$grade._id",
      "section_id":"$section._id",
      maxStudent:1
    }
  }
])

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