MongoDB Tutorial
- Home
- Introduction
- Installation
- Connection & Databases
- CRUD Operations
- Comparison Operators
- Logical Operators
- Array Operators
- Evaluation Operators
- Update Operators
- Projection & Sorting
- Cursor Methods
- Querying Nested Docs
- Upserts & Indexes
- Aggregation Framework
- Data Modeling
- Validations & Transactions
- Geospatial Queries
- Advanced Indexing
- MongoDB with Next.js
- Best Practices
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 descendingCompound 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")