skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search