Querying an array of arrays in MongoDB?

Use the $elemMatch operator with nested $in to query an array of arrays in MongoDB. This approach allows you to search for specific values within nested array structures.

Syntax

db.collection.find({
    "arrayField": {
        $elemMatch: {
            $elemMatch: {
                $in: ["searchValue"]
            }
        }
    }
});

Sample Data

db.arrayOfArraysDemo.insertMany([
    {
        "EmployeeName": "Larry",
        "EmployeeSkills": [["Java", "MongoDB", "MySQL", "SQL Server"]]
    },
    {
        "EmployeeName": "Mike",
        "EmployeeSkills": [["C", "C++"]]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c7f7a8d8d10a061296a3c5b"),
        ObjectId("5c7f7aa68d10a061296a3c5c")
    ]
}

Display All Documents

db.arrayOfArraysDemo.find().pretty();
{
    "_id": ObjectId("5c7f7a8d8d10a061296a3c5b"),
    "EmployeeName": "Larry",
    "EmployeeSkills": [
        [
            "Java",
            "MongoDB",
            "MySQL",
            "SQL Server"
        ]
    ]
}
{
    "_id": ObjectId("5c7f7aa68d10a061296a3c5c"),
    "EmployeeName": "Mike",
    "EmployeeSkills": [
        [
            "C",
            "C++"
        ]
    ]
}

Example: Query Array of Arrays

Find employees who have "MongoDB" as a skill in their nested array structure ?

db.arrayOfArraysDemo.find({
    'EmployeeSkills': {
        $elemMatch: {
            $elemMatch: {
                $in: ['MongoDB']
            }
        }
    }
}).pretty();
{
    "_id": ObjectId("5c7f7a8d8d10a061296a3c5b"),
    "EmployeeName": "Larry",
    "EmployeeSkills": [
        [
            "Java",
            "MongoDB",
            "MySQL",
            "SQL Server"
        ]
    ]
}

How It Works

  • The outer $elemMatch matches elements in the main array (EmployeeSkills)
  • The inner $elemMatch matches elements in the nested array
  • $in searches for the specified value within those nested elements

Conclusion

Use nested $elemMatch operators with $in to effectively query array of arrays in MongoDB. This pattern handles multi-level array structures and finds documents containing specific values in nested arrays.

Updated on: 2026-03-15T00:06:31+05:30

964 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements