簡體   English   中英

根據數組集合中的值獲取 _id 並插入到 mongodb 集合中

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

輸入:

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

在mongodb中如何從兩個集合中獲取gradeName和sectionName的_id並存儲在第三個集合中說mergeddetails

合並詳情:

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

其中grade_id是對應gradeName的_id,section_id是對應sectionName的_id請幫助mongodb quire我正在使用nodejs編寫API

您需要對這兩個集合使用$lookup

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
    }
  }
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM