Multi-key Indexing on an entire array with MongoDB?

Multi-key indexing in MongoDB allows you to index entire arrays and their nested elements efficiently. When you create an index on an array field, MongoDB automatically creates a multi-key index that indexes each array element separately.

Syntax

db.collection.createIndex({ "arrayField": 1 })
db.collection.find({ "arrayField": { "nestedField": "value" } })

Create Sample Data

db.demo277.insertMany([
    { "details": [{ "FirstName": "John" }] },
    { "details": [{ "FirstName": "David" }] },
    { "details": [{ "FirstName": "Chris" }] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e48fb21dd099650a5401a52"),
        ObjectId("5e48fb27dd099650a5401a53"),
        ObjectId("5e48fb2bdd099650a5401a54")
    ]
}

Verify Sample Data

db.demo277.find();
{ "_id": ObjectId("5e48fb21dd099650a5401a52"), "details": [{ "FirstName": "John" }] }
{ "_id": ObjectId("5e48fb27dd099650a5401a53"), "details": [{ "FirstName": "David" }] }
{ "_id": ObjectId("5e48fb2bdd099650a5401a54"), "details": [{ "FirstName": "Chris" }] }

Create Multi-key Index

db.demo277.createIndex({ "details": 1 });

Query Array Elements

Query to find documents where the details array contains an object with FirstName "David" ?

db.demo277.find({ "details": { "FirstName": "David" } });
{ "_id": ObjectId("5e48fb27dd099650a5401a53"), "details": [{ "FirstName": "David" }] }

How Multi-key Indexing Works

  • MongoDB automatically detects array fields and creates multi-key indexes
  • Each array element gets indexed separately for efficient queries
  • Queries can match exact array elements or use dot notation for nested fields

Conclusion

Multi-key indexing enables efficient querying of array elements in MongoDB. Create an index on the array field, and MongoDB automatically indexes each element for fast lookups and filtering operations.

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

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements