【问题标题】:Get the Patients Info from two Collections in MongoDB 3.6从 MongoDB 3.6 中的两个集合中获取患者信息
【发布时间】:2020-01-22 02:53:32
【问题描述】:

这里是两个名为Patients和Hospitals的集合,我需要获取PatientId的数据,该数据在以字符串数据格式存储在patientsId下的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 中处理数据类型转换

【问题讨论】:

  • 你试过这个db.Hospital.aggregate([ { $lookup: { from: "patient", localField: "PatientIds", foreignField: "_id", as: "PatientDetails" } } ])
  • 是的,我试过了
  • 我没有看到 PatientidsPatientDetails 对象内

标签: arrays mongodb mongodb-query aggregation-framework


【解决方案1】:

本地字段应为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"
    }
  }
]);

【讨论】:

  • 我尝试了第二个,它没有工作,顺便说一句,我使用的是 MongoDB 3.6 版本
  • @uttamrao MongoDB 3.6 版中没有toString(或$convert)运算符。它仅在更高版本 4.0 中可用。
  • 我现在如何在 MongoDB 3.6 中处理上述情况? @prasad_
  • 顺便说一句,我可以想到几件事(但是,您可能想在 Google 上做一些研究)。 (1) 将数据库更改为较新的版本, (2) 转换数据(将 PatientIds 更改为 ObjectId 类型 Patient 文档中带有_id 字符串值的字段(可以将该字段称为_idStr)。
  • @prasad_ 我们没有选择去更新版本或修改任何现有数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-06
  • 2019-07-17
  • 2019-01-13
相关资源
最近更新 更多