首页 > 解决方案 > 从 MongoDB 3.6 中的两个集合中获取患者信息

问题描述

这里是两个名为Patients 和Hospitals 的集合,我需要获取PatientId 的数据,该数据在以字符串数据格式存储在patientId 下的Hospital Collections 中,_id 存储为ObjectId 下面是详细信息:

**Hospital Collection :**
  {
            "_id" : ObjectId("5c04b943ff491824b806686a"),
            "email" : "ayoub.khial@gmail.com",
            "password" : "$2a$10$4Wt5Rn6udxREdXCIt3hGb.sKhKUKOlyiYKmLTjYG3SqEPKFSw9phq",
"PatientDetails" : {
                "WeekJoined" : "Monday", 
                "description" : "I",
            "PatientIds" : [
                    "5a0c6797fd3eb67969316ce2",
                    "5c07ada8ff49183284e509d1",
                    "5c07acc1ff49183284e509d0"
            ]
} }

**Patient Collection :**

    {
            "_id" : ObjectId("5a0c6797fd3eb67969316ce2"),
            "picture" : "http://placehold.it/150x150",
            "name" : "Genmom",
            "email" : "leilaware@genmom.com",
            "city" : "Rabat",
            "location" : {
                    "type" : "Point",
                    "coordinates" : [
                            -6.79387,
                            33.83957
                    ]
            }
    }
View Code :

 {
    "$lookup" : {
        "from" : "Patient",
        "localField" : "Hospital.PatientsDetails.PatientIds",
        "foreignField" : "_id",
        "as" : "PatientDetails"
    }
}

如何在 MongoDB 3.6 中的 Lookup 中处理数据类型转换

标签: arraysmongodbmongodb-queryaggregation-framework

解决方案


本地字段应该是 PatientDetails.PatientIds

如果你PatientIds是 ObjectIds 即

"PatientIds" : [
  ObjectId("5a0c6797fd3eb67969316ce2"),
  ObjectId("5c07ada8ff49183284e509d1"),
  ObjectId("5c07acc1ff49183284e509d0")
];

尝试这个

>>>db.hospitals.aggregate([
  {
    $lookup: {
      from: "patients",
      localField: "PatientDetails.PatientIds",
      foreignField: "_id",
      as: "PatientDetails"
    }
  }
]);

如果你PatientIds是字符串试试这个

>>>db.hospitals.aggregate([
  {
    $lookup: {
      from: "patients",
      let: { patientIds: "$PatientDetails.PatientIds" },
      pipeline: [
        {
          $match: { $expr: { $in: [{ $toString: "$_id" }, "$$patientIds"] } }
        }
      ],
      as: "PatientDetails"
    }
  }
]);


推荐阅读