Home > front end >  MongoDB - Querying inner object that is an array
MongoDB - Querying inner object that is an array

Time:02-08

I am new to MongoDB queries and looking for some guidance on how to retrieve documents that fit the search criteria. In particular, I need to find all the id(s) of the documents where the code is JPID i.e, "code": "JPID". We can assume the name of the collection is systems.

Since this is a nested object I thought of using the $unwid - but I am still stuck on how to do it. The example is very trivial. Any help and guidance is appreciated.

{
      "resourceType": "NamingSystem",
      "id": "example-id",
      "name": "Austalian Healthcare Identifier - Individual",
      "status": "active",
      "kind": "identifier",
      "date": "2015-08-31",
      "publisher": "HL7 Australia on behalf of NEHTA",
      "responsible": "HI Service Operator / NEHTA",
      "type": {
        "coding": [
          {
            "system": "http://hl7.org/fhir/v2/0203",
            "code": "JPID";
            "display": "National unique individual identifier"
          }
        ],
        "text": "IHI"
      },
      "description": "Australian HI Identifier as established by relevant regulations etc",
      "uniqueId": [
        {
          "type": "oid",
          "value": "1.2.36.1.2001.1003.0",
          "comment": "This value is used in Australian CDA documents"
        },
        {
          "type": "uri",
          "value": "http://ns.electronichealth.net.au/id/hi/ihi/1.0",
          "preferred": true,
          "period": {
            "start": "2015-08-21"
          }
        }
      ]
    }

CodePudding user response:

  1. You can find all documents that contain at least one element in type.coding array by simple match the code element with the value JPID:

    db.system.find({
     "type.coding.code": "JPID"
    })
    

It is recommended to create and index on {"type.coding.code":1} so your searches to perform faster on this field.

playground

  1. If you need to find all documents and filter only the array entries having the code:"JPID" you can use $filter as follow:

    db.system.aggregate([
    {
     $match: {
       "type.coding.code": "JPID"
     }
    },
    {
     $addFields: {
       "type.coding": {
         "$filter": {
          "input": "$type.coding",
          "as": "tc",
          "cond": {
            $eq: [
              "$$tc.code",
              "JPID"
              ]
           }
         }
       }
     }
    }
    ])
    

playground(filter)

  •  Tags:  
  • Related