Upserts & Indexes

Efficiency and performance are key to any database. MongoDB provides Upserts for convenient data management and Indexes for high-speed queries.

1. What is an Upsert?

An Upsert (Update + Insert) is an option for update operations. If a document matches the query, it is updated. If no document matches, a new document is inserted.

// Example of an Upsert
db.users.updateOne(
  { email: "new@example.com" }, // Query
  { $set: { name: "New User", joined: new Date() } }, // Values
  { upsert: true } // Option
)

2. Understanding Indexes

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a Collection Scan (scan every document in a collection) to select those documents that match the query.

Single Field Index

Creates an index on a single field in a collection.

db.users.createIndex({ email: 1 }) // 1 for ascending, -1 for descending

Compound Index

Creates an index on multiple fields. The order of fields matters (ESR Rule: Equality, Sort, Range).

db.users.createIndex({ status: 1, age: -1 })

TTL Index (Time-To-Live)

Allows documents to be automatically deleted after a certain period of time (e.g., for session data or logs).

db.sessions.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 })

Text Index

Required for performing full-text search on string content.

db.posts.createIndex({ content: "text" })

3. Managing Indexes

  • Get All Indexes: db.users.getIndexes()
  • Drop an Index: db.users.dropIndex("index_name")
  • Explain Query Performance: db.users.find({email: "..."}).explain("executionStats")
Warning: While indexes make reads faster, they make writes slightly slower because the index must be updated every time a document is inserted or modified. Use them strategically!