How to index my collection to use a compound multikey index?

To create a compound multikey index on your MongoDB collection, use the createIndex() method (modern replacement for the deprecated ensureIndex()). A compound multikey index combines multiple fields where at least one field contains array values.

Syntax

db.collection.createIndex({
    "field1": 1,
    "arrayField.nestedField": 1
});

Create Sample Data

First, let's create the compound multikey index on our collection ?

db.demo678.createIndex({id: 1, "details.userId": 1});
{
    "createdCollectionAutomatically": true,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Now insert a document with array fields ?

db.demo678.insertOne({
    id: 101,
    "details": [
        {
            "userId": "1001",
            "userName": "Chris"
        },
        {
            "userId": "1002", 
            "userName": "David"
        }
    ],
    "otherDetails": [
        {
            CountryName: "US",
            EmailId: ["Chris@gmail.com", "David@gmail.com"]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5ea4276904263e90dac943fc")
}

Verify the Document

Display the document to confirm the structure ?

db.demo678.find();
{
    "_id": ObjectId("5ea4276904263e90dac943fc"),
    "id": 101,
    "details": [
        { "userId": "1001", "userName": "Chris" },
        { "userId": "1002", "userName": "David" }
    ],
    "otherDetails": [
        { "CountryName": "US", "EmailId": ["Chris@gmail.com", "David@gmail.com"] }
    ]
}

Key Points

  • Use createIndex() instead of deprecated ensureIndex()
  • The index on details.userId becomes multikey because details is an array
  • MongoDB automatically detects multikey indexes when array values are indexed

Conclusion

Compound multikey indexes efficiently query documents with array fields. Use createIndex() with dot notation to index nested fields within arrays, enabling fast queries on both scalar and array-based fields.

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

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements