MongoDBQuestion 04 of 8
Searching a large collection
Answer out loud or in your head first, then compare.
Answer
I start with the real query and its execution plan. The index should support its filters and sorting.
JavaScript
db.orders.createIndex({ customerId: 1, createdAt: -1 });
db.orders.find({ customerId: 'u1' })
.sort({ createdAt: -1 }).limit(20)
.explain('executionStats');I check: the number of returned results versus documents and keys examined, collection scans and the cost of sorting.
In practice: I limit the returned fields and use sensible pagination; with large offsets I consider a cursor on an indexed key.
Pitfall: indexes cost memory, space and write time. I don't create an index on every field, nor assume every regex will use one efficiently.
How did it go? Be honest — “Not yet” puts the question on your review list.