Using object as key for finding values in MongoDB

To use an object field as a key for finding values in MongoDB, use dot notation to access nested object properties in the projection parameter of the find() method.

Syntax

db.collection.find({}, {"objectName.fieldName": 1});

Sample Data

Let us create a collection with nested object documents −

db.demo361.insertMany([
    {"details": {"FirstName": "Chris", "LastName": "Brown"}},
    {"details": {"FirstName": "David", "LastName": "Miller"}},
    {"details": {"FirstName": "John", "LastName": "Doe"}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e56a61f54a481fef8ec7a19"),
        ObjectId("5e56a62854a481fef8ec7a1a"),
        ObjectId("5e56a63654a481fef8ec7a1b")
    ]
}

Display all documents from the collection −

db.demo361.find();
{"_id": ObjectId("5e56a61f54a481fef8ec7a19"), "details": {"FirstName": "Chris", "LastName": "Brown"}}
{"_id": ObjectId("5e56a62854a481fef8ec7a1a"), "details": {"FirstName": "David", "LastName": "Miller"}}
{"_id": ObjectId("5e56a63654a481fef8ec7a1b"), "details": {"FirstName": "John", "LastName": "Doe"}}

Example: Project Specific Object Field

Use dot notation to project only the LastName field from the nested details object −

db.demo361.find({}, {"details.LastName": 1});
{"_id": ObjectId("5e56a61f54a481fef8ec7a19"), "details": {"LastName": "Brown"}}
{"_id": ObjectId("5e56a62854a481fef8ec7a1a"), "details": {"LastName": "Miller"}}
{"_id": ObjectId("5e56a63654a481fef8ec7a1b"), "details": {"LastName": "Doe"}}

Key Points

  • Use "objectName.fieldName": 1 in projection to include specific nested fields.
  • The _id field is included by default unless explicitly excluded with "_id": 0.
  • Dot notation works for deeply nested objects: "level1.level2.field": 1.

Conclusion

MongoDB's dot notation in projection allows you to selectively retrieve specific fields from nested objects. This technique is essential for optimizing query performance and reducing data transfer when working with complex document structures.

Updated on: 2026-03-15T02:37:28+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements