MongoDB聚合属性模式管道/查询

2024-10-03 11:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我的属性模式(https://www.mongodb.com/blog/post/building-with-patterns-the-attribute-pattern)字段如下所示:

"cmr_diag": [{
        "name": "shd?",
        "value": {
            "$numberDouble": "1"
        }
    }, {
        "name": "ischemic_hd",
        "value": {
            "$numberDouble": "1"
        }
    }, {
        "name": "non-ischemic_dcmp",
        "value": {
            "$numberDouble": "1"
        }
    }, {
        "name": "myocarditis",
        "value": {
            "$numberDouble": "0"
        }
    }, {
        "name": "hcm",
        "value": {
            "$numberDouble": "0"
        }
    }, {
        "name": "amyloidosis",
        "value": {
            "$numberDouble": "0"
        }
    }, {
        "name": "toxic_cmp",
        "value": {
            "$numberDouble": "1"
        }
      .
      .
      .

我想创建一个聚合管道,用于查找所有仅患有缺血性心脏病的患者,而所有其他可能的疾病都是0。但是,我不确定如何创建此查询


Tags: namehttpscom属性valuemongodbwwwwith
1条回答
网友
1楼 · 发布于 2024-10-03 11:25:52

您可以使用$elemMatch来识别具有特定属性的患者

如果要排除所有其他属性,请使用$reduce对所有属性的值求和,并匹配其中的count=1

db.collection.aggregate([
   {$match: {
       cmr_diag: {
           $elemMatch: {
                  name: "ischemic_hd",
                  value: { "$numberDouble": "1" }
           }
       }
   }},
   {$addFields: {
       diagcount: {
          $reduce: {
              input: "$cmr_diag",
              initialValue: 0,
              in: {$sum: ["$$value","$$this.value.$numberDouble"]}
          }
       }
    }},
    {$match: { diagcount: 1}}
])

相关问题 更多 >