Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to MongoDB
MongoDB Indexing Best Practices

MongoDB Indexing Best Practices

MongoDB3,047 viewsBy Admin
mongodbindexingbestpractices

Advertisement

Indexes in MongoDB

Like SQL, MongoDB indexes speed up queries. Without them, MongoDB scans every document (a "collection scan").

Creating Indexes

db.users.createIndex({ email: 1 });          // ascending
db.users.createIndex({ age: -1 });           // descending
db.users.createIndex({ name: 1, age: -1 });  // compound
db.users.createIndex({ email: 1 }, { unique: true });

Check Performance with explain()

db.users.find({ email: "x@y.com" }).explain("executionStats");
// Look for IXSCAN (good) vs COLLSCAN (bad)

Best Practices

  • Index fields used in queries, sorts, and joins.
  • Put equality fields before range fields in compound indexes.
  • Use unique for emails/usernames.
  • Don't over-index — writes slow down.

Text Indexes for Search

db.posts.createIndex({ title: "text", body: "text" });
db.posts.find({ $text: { $search: "mongodb" } });

FAQs

What is the _id index?

MongoDB auto-creates a unique index on _id for every collection. More in our MongoDB section.

How do I see existing indexes?

Run db.collection.getIndexes().

Advertisement