Home > Back-end >  MongoDB -Query documents where nested array fields is equal to some value
MongoDB -Query documents where nested array fields is equal to some value

Time:12-09

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:

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

but it returns no documents.

CodePudding user response:

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

  • Related