arrays - 从 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 中处理数据类型转换
解决方案
本地字段应该是 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"
}
}
]);
推荐阅读
- sql - Postgres 函数返回太多列
- reactjs - React JS 中的列表渲染
- mysql - 是否可以确定哪个键触发“重复键”错误?
- android - Firestore:通过逻辑 OR 在嵌套地图/数组中的多个字段上搜索/过滤功能
- python - Python:解决这个凌乱的 if else 结构更好
- python-3.x - 通过表单提交数据但未存储在数据库中
- java - @PathVariable、@RequestParam 和 @RequestBody 之间的区别
- python - TensorFlow 通用句子编码器 (lite) 崩溃
- r - 如何在 getSymbols 中返回从星期一开始的每周数据
- c# - 如何在 Unity 中修复“错误 CS1061:‘GoogleMobileAdsSettings’不包含‘IsAdMobEnabled’的定义”