Set condition in MongoDB nested document?

To set conditions in MongoDB nested documents, use dot notation to navigate through the nested structure and apply comparison operators like $gt, $lt, or $eq to filter documents based on nested field values.

Syntax

db.collection.find({
    "parentField.nestedField.deepField": { $operator: value }
});

Sample Data

db.demo688.insertMany([
    {
        information: {
            id: 1,
            details: [
                {
                    otherDetails: {
                        values: 75
                    }
                }
            ]
        }
    },
    {
        information: {
            id: 2,
            details: [
                {
                    otherDetails: {
                        values: 78
                    }
                }
            ]
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("...")
    ]
}

Display All Documents

db.demo688.find();
{ "_id" : ObjectId("5ea57986a7e81adc6a0b3965"), "information" : { "id" : 1, "details" : [ { "otherDetails" : { "values" : 75 } } ] } }
{ "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }

Example: Find Documents with Values Greater Than 75

db.demo688.find({
    "information.details.otherDetails.values": { $gt: 75 }
});
{ "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }

Key Points

  • Use dot notation to traverse nested document structures: "parent.child.grandchild"
  • Apply comparison operators like $gt, $lt, $gte, $lte on deeply nested fields
  • MongoDB automatically searches through array elements when using dot notation

Conclusion

Dot notation combined with comparison operators provides powerful querying capabilities for nested documents in MongoDB. This approach allows precise filtering on deeply nested field values without complex aggregation pipelines.

Updated on: 2026-03-15T03:37:55+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements