Home > Mobile >  MongoDB filtering nested structure
MongoDB filtering nested structure

Time:08-29

I have the following data structure:

{
    "_id": ObjectId("630bd746956bba0f6f0ba448"),
    "a": [
      {
        "b": [
          [
            [
              {
                "c": "aaa"
              }
            ]
          ]
        ]
      }
    ],
  }

How can I filter all documents with the value aaa for their nested c property? I tried using this query: db.collection.find({"a.b.c": "aaa"}) but it doesn't work.

Link to Mongo playground.

CodePudding user response:

To search in an array, you need to use $elemMatch, and where you have nested arrays, the query will be:

db.collection.find({
  "a": {
    "$elemMatch": {
      "b": {
        "$elemMatch": {
          "$elemMatch": {
            "$elemMatch": {
              "c": "aaa"
            }
          }
        }
      }
    }
  }
})

Link to Mongo Playground

CodePudding user response:

In order to match documents that contain an array field, you need to use $elemMatch operator. Try this query out:

db.collection.find({
  "a.b": {
    "$elemMatch": {
      "$elemMatch": {
        "$elemMatch": {
          "c": "aaa"
        }
      }
    }
  }
})

Documentation for reference: https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/

  • Related