如何查询多个MongoDB集合和NodeJS?

时间:2020-02-08 05:18:38

标签: node.js mongodb mongodb-query

我在MongoDB中有三个集合。

Drug JSON中,使用MEDID从Composition JSON获取其相应的CMID。使用该CMID,可以从Chemicals JSON获取其相应的化学名称,然后将其medidcmid及其name存储在一个数组中。

我正在使用NodeJS。请帮助我,谢谢。

药物收集

{ 
   "MEDID":"AAA001-01",
   "BRANDNAME":"TASULIN D",
   "MEDTYPECODE":"CAP",
   "DOSE":"",
   "DOSEUNIT":"",
   "CHEMICAL1":"TAMSULSIN HYDROCHLORIDE",
   "CHEMICAL2":"DUTASTERIDE",
   "CHEMICAL3":"",
   "CHEMICAL4":"",
   "CHEMICAL5":"",
   "CHEMICAL6":"",
   "CHEMICAL7":"",
   "CHEMICAL8":"",
   "CHEMICAL9":"",
   "CHEMICAL10":"",
   "CHEMICAL11":"",
   "SPECIALITY":"GEN",
   "MANUFACTURER":"IPCA",
   "MFTID":"xyz123"
}

组合集合

{"MEDID":"AAA001-01","CMID":"ABC001"},
{"MEDID":"AAA001-01","CMID":"ABC002"}

化学馆藏

{"CMID":"ABC001","Name":"TAMSULSIN HYDROCHLORIDE"},
{"CMID":"ABC002","Name":"DUTASTERIDE"},

1 个答案:

答案 0 :(得分:0)

db.drug.aggregate([
   {
     $lookup:
       {
         from: "composition",
         localField: "medid",
         foreignField: "medid",
         as: "composition"
       }
  },
    $lookup:
       {
         from: "chemical",
         localField: "composition.cmid",
         foreignField: "cmid",
         as: "chemical"
       }
   },
    $group: {
        _id: "$medid",
        cmid: { $first: "$composition.cmid" },
        name: { $first: "$chemical.name" }
]);