从MongoDB 3.6的两个集合中获取患者信息

问题描述 投票:-1回答:1

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

**Hospital Collection :**
  {
            "_id" : ObjectId("5c04b943ff491824b806686a"),
            "email" : "[email protected]",
            "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" : "[email protected]",
            "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中处理数据类型转换

arrays mongodb mongodb-query aggregation-framework
1个回答
0
投票

本地字段应为PatientDetails.PatientIds

如果您的PatientIds作为ObjectId,即

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

© www.soinside.com 2019 - 2024. All rights reserved.