MongoDB large collection and slow search? How to fix?

For large MongoDB collections with slow search performance, create indexes on frequently queried fields. Use the createIndex() method to optimize query execution time significantly.

Syntax

db.collection.createIndex({ field: 1 });
db.collection.createIndex({ field1: 1, field2: -1 });

Create Index and Sample Data

First, create an index on the field you'll search frequently:

db.demo661.createIndex({ListOfName: 1});
{
    "createdCollectionAutomatically": true,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Insert sample documents into the collection:

db.demo661.insertMany([
    { _id: 1, ListOfName: ["John", "Robert", "David"] },
    { _id: 2, ListOfName: ["Mike", "Sam"] },
    { _id: 3, ListOfName: ["John", "David", "Bob"] }
]);
{ "acknowledged": true, "insertedIds": [1, 2, 3] }

Verify Sample Data

Display all documents to confirm the data structure:

db.demo661.find();
{ "_id": 1, "ListOfName": ["John", "Robert", "David"] }
{ "_id": 2, "ListOfName": ["Mike", "Sam"] }
{ "_id": 3, "ListOfName": ["John", "David", "Bob"] }

Optimized Search Query

Use $all operator to find documents containing all specified array elements. The index speeds up this search:

db.demo661.find({"ListOfName": {"$all": ["John", "David"]}});
{ "_id": 1, "ListOfName": ["John", "Robert", "David"] }
{ "_id": 3, "ListOfName": ["John", "David", "Bob"] }

Key Benefits

  • Faster queries: Indexes reduce query execution time from O(n) to O(log n)
  • Reduced disk I/O: MongoDB can locate data without scanning entire collection
  • Better performance: Essential for collections with thousands or millions of documents

Conclusion

Creating indexes on frequently searched fields is the primary solution for slow queries in large MongoDB collections. Always index fields used in find(), sort(), and aggregation operations for optimal performance.

Updated on: 2026-03-15T03:26:10+05:30

486 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements