How do you find a MongoDB record that is two level deep?

To find a MongoDB record that is two level deep, use the $where operator with a JavaScript function to loop through nested objects and find matching field values.

Syntax

db.collection.find({
    $where: function() {
        for (var field in this) {
            if (this[field]["nestedField"] == "searchValue") {
                return true;
            }
        }
        return false;
    }
})

Sample Data

db.demo468.insertMany([
    {
        "_id": new ObjectId(),
        "FirstPosition": {
            "StudentName": "Chris",
            "StudentAge": 23
        },
        "SecondPosition": {
            "StudentName": "David",
            "StudentAge": 20
        }
    },
    {
        "_id": new ObjectId(),
        "FirstPosition": {
            "StudentName": "Carol",
            "StudentAge": 21
        },
        "SecondPosition": {
            "StudentName": "John",
            "StudentAge": 22
        }
    }
])
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e804e2fb0f3fa88e2279069"),
        ObjectId("5e804fb0b0f3fa88e227906a")
    ]
}

Display All Documents

db.demo468.find()
{ "_id": ObjectId("5e804e2fb0f3fa88e2279069"), "FirstPosition": { "StudentName": "Chris", "StudentAge": 23 }, "SecondPosition": { "StudentName": "David", "StudentAge": 20 } }
{ "_id": ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition": { "StudentName": "Carol", "StudentAge": 21 }, "SecondPosition": { "StudentName": "John", "StudentAge": 22 } }

Example: Find Record with Nested StudentName "John"

db.demo468.find({
    $where: function() {
        for (var i in this) {
            if (this[i]["StudentName"] == "John") {
                return true;
            }
        }
        return false;
    }
})
{ "_id": ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition": { "StudentName": "Carol", "StudentAge": 21 }, "SecondPosition": { "StudentName": "John", "StudentAge": 22 } }

How It Works

The $where operator executes JavaScript code for each document. The function loops through all top-level fields (FirstPosition, SecondPosition) and checks if any nested object contains the target value. It returns true for matching documents.

Conclusion

Use $where with JavaScript loops to search through multiple nested objects when you need to find records at two levels deep. This approach works when the nested structure varies or when using dot notation is impractical.

Updated on: 2026-03-15T03:05:12+05:30

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements