Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB query documents wher nested array fields is equal to some value

I have a json object:

"ownershipSheetB": {
    "lrUnitShares": [{
            "description": "blabla1",
            "lrOwners": [{
                    "lrOwnerId": 35780527,
                    "name": "somename1",
                    "address": "someadress1",
                    "taxNumber": "12345678910"
                }
            ],
            "lrUnitShareId": 29181970,
            "subSharesAndEntries": [],
            "orderNumber": "1"
        }, {
            "description": "blabla2",
            "lrOwners": [{
                    "lrOwnerId": 35780528,
                    "name": "somename2",
                    "address": "someadress2",
                    "taxNumber": "12345678911"
                }
            ],
            "lrUnitShareId": 29181971,
            "subSharesAndEntries": [],
            "orderNumber": "2"
        }
    ],
    "lrEntries": []
}

I would like to query all documents that have taxNumber field equal to some string (say "12345678911" from the example above).

I have tried this query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"ownershipSheetB.lrUnitShares": { "lrOwners": {"taxNumber": "12345678910"}}}

but it returns no documents.

>Solution :

Solution 1: With dot notation

db.collection.find({
  "ownershipSheetB.lrUnitShares.lrOwners.taxNumber": "12345678910"
})

Demo Solution 1 @ Mongo Playground


Solution 2: With $elemMatch

db.collection.find({
  "ownershipSheetB.lrUnitShares": {
    $elemMatch: {
      "lrOwners": {
        $elemMatch: {
          "taxNumber": "12345678910"
        }
      }
    }
  }
})

Demo Solution 2 @ Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading