Single field indexes

For this illustration, we will use the sweetscomplete.purchases collection, which we described in Chapter 5, Building Complex Queries Using Aggregation. To avoid flipping pages, here is the first document in this collection to remind you of its structure:

Consider the following query:

db.purchases.find( {},     {_id:0, date:1, "customer.name":1, "customer.country":1}) .sort( {"customer.country":1, date:-1} );

If you frequently run queries which involve the date field, then it would improve the performance of find() and sort() to index this field. To create the index, you can use the collection method createIndex(), specifying ...

Get MongoDB 4 Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.