【问题标题】:MongoDB Aggregation Attribute Pattern Pipeline/QueryMongoDB 聚合属性模式管道/查询
【发布时间】:2020-12-17 20:48:54
【问题描述】:

我的属性模式 (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"
        }
      .
      .
      .

我想创建一个聚合管道来查找所有只有 ischemic_hd 的患者,而所有其他可能的疾病都是 0。但是我不确定如何创建此查询?

【问题讨论】:

  • 您能否在帖子中添加一个示例,说明您最终需要什么?

标签: python mongodb mongodb-query aggregation-framework pymongo


【解决方案1】:

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

如果要排除其他所有内容,请使用$reduce 将所有属性的值相加,并匹配 where 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}}
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2020-07-27
    • 2019-06-18
    相关资源
    最近更新 更多