1

I have nested json array and want to fetch patient_ids whose code value is M18.1 using mongo db query.

   {"zip":"04903","specialty":"cardiac","number_of_patients":250,"data":[{"gender":"male","age_data":[{"age":1,"diagnostic_data":[{"standard":"ICD","version":"9","disease_info":[{"code":"I15","patient_ids":["101","102","103"]},{"code":"I11","patient_ids":["101","110"]}]},{"standard":"ICD","version":"10","disease_info":[{"code":"M18.1","patient_ids":["101","110","111","112","113"]},{"code":"M19.1","patient_ids":["101","110","111","112","113"]}]}]},{"age":3,"diagnostic_data":[{"standard":"ICD","version":"9","disease_info":[{"code":"I15","patient_ids":["101","102","103"]},{"code":"I11","patient_ids":["101","110"]}]},{"standard":"ICD","version":"10","disease_info":[{"code":"M18.1","patient_ids":["101","110","111","112","113"]},{"code":"M19.1","patient_ids":["101","110","111","112","113"]}]}]}]}]}

I have tried with aggregate,$elemMatch,$project and $filter, it's working with one level of array.

db.collectionnale.aggregate([
{
"$match" : {
       "data" : {      
               "$elemMatch" : {
                  "$and" : [
                     { "gender" : "male" }
                    ]
                    }
         }
   }
  },{
   "$project" : {
       "specialty":1,
       "data": {                  
          "$filter" : {
             "input" : "$data",
             "as" : "data",
             "cond" : { "$eq" : [ "$$data.gender", "male" ] }

             }
          }
       } 
}])

1 Answer 1

1

Querying nested array is not that easy so you can $unwind your arrays first by using aggregate and then apply your query.

db.collectionnale.aggregate([
  { $unwind: "$data" },
  { $unwind: "$data.age_data" },
  { $unwind: "$data.age_data.diagnostic_data" },
  { $unwind: "$data.age_data.diagnostic_data.disease_info" },
  {
    $match:
      { "data.age_data.diagnostic_data.disease_info.code": 'M18.1' }
  },
  {
    "$group": {
      "_id": 0,
      "patientIds": { "$push": "$data.age_data.diagnostic_data.disease_info.patient_ids" }
    }
  },
  {
    "$project": {
      "_id": 0,
      "patientIds": {
        "$reduce": {
          "input": "$patientIds",
          "initialValue": [],
          "in": { "$setUnion": ["$$value", "$$this"] }
        }
      }
    }
  }
])

Output:

 {
        "patientIds" : [ 
            "101", 
            "110", 
            "111", 
            "112", 
            "113"
        ]
    }
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.