mongodb - 如何创建基于唯一元素作为字段的聚合?
问题描述
我正在尝试基于诊断类型聚合文档,并在更高级别patientKey
和encounterKey
. 这是文档的样子:
{
"_id" : ObjectId("...."),
"patientKey" : 1,
"encounterKey" : 2,
"diagnosisType" : "medical_history",
"diagnosisCode" : "Z87.81",
}
{
"_id" : ObjectId("...."),
"patientKey" : 1,
"encounterKey" : 2,
"diagnosisType" : "problem_list",
"diagnosisCode" : "2x.2",
}
{
"_id" : ObjectId("...."),
"patientKey" : 1,
"encounterKey" : 3,
"diagnosisType" : "medical_history",
"diagnosisCode" : "D21.01",
}
{
"_id" : ObjectId("...."),
"patientKey" : 1,
"encounterKey" : 3,
"diagnosisType" : "medical_history",
"diagnosisCode" : "X2.31",
}
{
"_id" : ObjectId("...."),
"patientKey" : 1,
"encounterKey" : 3,
"diagnosisType" : "problem_list",
"diagnosisCode" : "p.2342",
}
这就是我希望聚合的样子:
{
"patientKey": 1,
"encounters":[{
encounterKey: 2,
medical_history: [Z87.81],
problem_list: [2x.2]
},
{
encounterKey: 3,
medical_history: [D21.01, X2.31],
problem_list: [p.2342]
}]
}
有什么想法可以解决这个问题吗?
我已经尝试了以下病史和问题列表,我最初的想法是首先在问题列表上聚合,然后在病历上聚合,然后合并集合,然后根据遇到的情况进行另一个聚合,最后再对患者 ID 进行聚合。
但是结合异构文档是一个问题。
db.collections.aggregate([
{$match:{diagnosisType:"Problem List"}},
{$group:{_id:"$encounterKey",
"ProblemList": {$push:{$concat:"$diagnosisCode"}},
"durableKey":{$first:"$durableKey"}}},
{$project:{_id:0,
encounterKey:"$_id",
ProblemList:1,
durableKey:1}},
{$out:"output"}
],{
allowDiskUse: true
})
解决方案
您可以使用以下聚合:
db.col.aggregate([
{
$group: {
_id: { patientKey: "$patientKey", encounterKey: "$encounterKey", diagnosisType: "$diagnosisType" },
problem_list: { $push: "$diagnosisCode" }
}
},
{
$group: {
_id: { patientKey: "$_id.patientKey", encounterKey: "$_id.encounterKey" },
encounters: { $push: { k: "$_id.diagnosisType", v: "$problem_list" } }
}
},
{
$project: {
encounters: { $arrayToObject: "$encounters" }
}
},
{
$group: {
_id: "$_id.patientKey",
encounters: {
$push: {
encounterKey: "$_id.encounterKey",
problem_list: "$encounters.problem_list",
medical_history: "$encounters.medical_history"
}
}
}
},
{
$project: {
patientKey: "$_id",
_id: 0,
encounters: 1
}
}
])
基本上你需要几个$group阶段来积累数据。此外,您必须使用$arrayToObject动态构建您的 JSON 密钥。
输出:
{
"patientKey" : 1,
"encounters" : [
{
"encounterKey" : 2,
"problem_list" : [
"2x.2"
],
"medical_history" : [
"Z87.81"
]
},
{
"encounterKey" : 3,
"problem_list" : [
"p.2342"
],
"medical_history" : [
"D21.01",
"X2.31"
]
}
]
}
推荐阅读
- c - vs代码调试器(lldb)不显示正确的值
- javascript - 在 div 中居中 svg
- reactjs - 尝试通过更改状态挂钩来更改 React Style 属性
- jquery - 我可以在 Laravel + vue App 中使用 jQuery Ajax 吗?
- javascript - 外部属性为空时是否可以拥有内部属性?
- java - Selenium 在浏览器(Chrome)隐藏时失败,但在浏览器可见时成功
- java - 关闭应用程序后不执行定期作业?
- .net-core - What is a BindAsync method with two params in the IBinding interface
- ruby - 在 post_install Podfile 挂钩中删除链接的 Pods_framework
- tensorflow - Try/Except 不适用于 tflearn。请