Array index or indexing inner items in MongoDB to fetch values

MongoDB uses dot notation to access nested fields and array elements. You can create indexes on nested fields to improve query performance when searching within embedded documents or arrays.

Syntax

// Create index on nested field
db.collection.createIndex({"field.nestedField": 1});

// Query nested field
db.collection.find({"field.nestedField": "value"});

Sample Data Setup

Let's create a collection with nested documents and add an index on the nested field ?

db.demo323.insertMany([
    {"details": {"Name": "Chris", "Age": 34}},
    {"details": {"Name": "David", "Age": 31}},
    {"details": {"Name": "Bob", "Age": 28}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e51157af8647eb59e56206e"),
        ObjectId("5e511581f8647eb59e56206f"),
        ObjectId("5e511589f8647eb59e562070")
    ]
}

Create Index on Nested Field

db.demo323.createIndex({"details.Name": 1});
{
    "createdCollectionAutomatically": false,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Query Documents

Display all documents in the collection ?

db.demo323.find();
{"_id": ObjectId("5e51157af8647eb59e56206e"), "details": {"Name": "Chris", "Age": 34}}
{"_id": ObjectId("5e511581f8647eb59e56206f"), "details": {"Name": "David", "Age": 31}}
{"_id": ObjectId("5e511589f8647eb59e562070"), "details": {"Name": "Bob", "Age": 28}}

Query Nested Field

Find documents where the nested Name field equals "Bob" ?

db.demo323.find({"details.Name": "Bob"});
{"_id": ObjectId("5e511589f8647eb59e562070"), "details": {"Name": "Bob", "Age": 28}}

Conclusion

Use dot notation to access nested fields in MongoDB. Creating indexes on frequently queried nested fields improves performance. The syntax field.nestedField allows efficient querying of embedded documents.

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

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements