0

I have Attribute Patterned (https://www.mongodb.com/blog/post/building-with-patterns-the-attribute-pattern) field that looks like this:

"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"
        }
      .
      .
      .

I'd like to create an aggregation pipeline that finds all patients with ONLY ischemic_hd, while all other possible illnesses are 0. I am not sure how to create this query however?

1
  • Can you add to the post an example of exactly what you need for the end result? Commented Aug 28, 2020 at 23:32

1 Answer 1

1

You can use $elemMatch to identify patients with a specific attribute.

If you want to exclude everything else, use $reduce to sum up the value of all of the attributes, and match 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}}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.