MongoDB – Querying inner object that is an array Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of MongoDB – Querying inner object that is an array without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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

Answer

  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)

We are here to answer your question about MongoDB – Querying inner object that is an array - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji