我的患者模型是这样的:
PatientModel=new Schema({
"PatientID":{type:String},
"PatientGender":{type:String},
"PatientDateOfBirth":{type:Date},
"PatientRace":{type:String},
"PatientMaritalStatus":{type:String},
"PatientLanguage":{type:String},
"PatientPopulationPercentageBelowPoverty":{type:Number},
"FirstName":{type:String},
"LastName":{type:String},
"City":{type:String}
});
和疾病模型
DiseaseModel=new Schema({
"PatientID":{type:String},
"AdmissionID":{type:Number},
"PrimaryDiagnosisCode":{type:String},
"Disease":{type:String}
});
我希望" City" (在PatientModel中)按降序排列,限制在10个城市。我如何在nodejs中编写查询?
疾病的样本数据:
{
"PatientID": "170EF37F-1098-462C-838F-C56C5455CB98",
"AdmissionID": 3,
"PrimaryDiagnosisCode": "C00.1",
"PrimaryDiagnosisDescription": "Malignant neoplasm of external lower lip"
}
患者的样本数据:
{
"PatientID": "170EF37F-1098-462C-838F-C56C5455CB98",
"PatientGender": "Male",
"PatientDateOfBirth": "1951-09-26 08:48:36.700",
"PatientRace": "White",
"PatientMaritalStatus": "Married",
"PatientLanguage": "English",
"PatientPopulationPercentageBelowPoverty": 14.15,
"FirstName": "BENJAMIN",
"LastName": "YIN",
"City": "Gokak",
}
答案 0 :(得分:0)
MongoDB不支持联接。所以有了这个模型,我认为不可能。你可以做的是,在你的diseases
中添加一个PatientModel
字段,这是一个字符串数组。像这样:
PatientModel=new Schema({
"PatientID":{type:String},
"PatientGender":{type:String},
"PatientDateOfBirth":{type:Date},
"PatientRace":{type:String},
"PatientMaritalStatus":{type:String},
"PatientLanguage":{type:String},
"PatientPopulationPercentageBelowPoverty":{type:Number},
"FirstName":{type:String},
"LastName":{type:String},
"City":{type:String},
"Diseases": { type: [String] }
});
然后您可以简单地使用此聚合查询。这是针对Mongo Shell的。但是Mongoose相当于此功能。
db.patients.aggregate([
{ $match: { Diseases: your_specified_disease } },
{ $group: {
_id: { city: "$City" },
patients_count: { $sum : 1 }
} },
{ $sort: { patients_count: -1 } },
{ $limit: 10 }
]);
我刚试过它。它正在发挥作用。
修改强>
如果您不愿意更改架构,那么就像Neil建议的那样,您可以使用$lookup
。在这种情况下,您的查询应该是这样的:
db.diseases.aggregate([
{ $match: { Disease: your_specified_disease } },
{ $lookup: {
from: "patients",
localField: "PatientID",
foreignField: "PatientID",
as: "Patient"
}
},
{ $group: {
_id: { city: "$Patient.City" },
patients_count: { $sum : 1 }
} },
{ $sort: { patients_count: -1 } },
{ $limit: 10 }
])
我没有测试过这个,因为我没有你拥有的所有数据。但请测试一下,让我知道它是否适合你。