MongoDb - MongoDB indexing and searching
Great topic — let’s break down MongoDB indexing and searching step by step.
1. What is Indexing in MongoDB?
-
An index is a data structure (usually a B-Tree) that improves the speed of queries.
-
Without an index, MongoDB performs a collection scan (checks every document).
-
With indexes, MongoDB can quickly locate matching documents.
2. Creating Indexes
You create indexes with createIndex()
:
a) Single Field Index
db.users.createIndex({ name: 1 })
-
1
= ascending order -
-1
= descending order -
Used for queries like:
db.users.find({ name: "Alice" })
b) Compound Index (Multiple Fields)
db.users.createIndex({ age: 1, name: -1 })
-
Useful when queries use both fields.
-
Order matters:
{ age: 1, name: -1 }
is not the same as{ name: -1, age: 1 }
.
c) Unique Index
db.users.createIndex({ email: 1 }, { unique: true })
-
Prevents duplicate emails.
d) Text Index (for Searching Text)
db.articles.createIndex({ content: "text", title: "text" })
-
Enables text search queries:
db.articles.find({ $text: { $search: "mongodb indexing" } })
e) Geospatial Index
For location-based data:
db.places.createIndex({ location: "2dsphere" })
Query with:
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [40, -73] },
$maxDistance: 5000
}
}
})
f) TTL (Time-to-Live) Index
Automatically deletes documents after a time:
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
-
Deletes docs 1 hour after
createdAt
value.
3. Searching in MongoDB
a) Equality Match
db.users.find({ name: "Alice" })
b) Range Queries
db.users.find({ age: { $gt: 20, $lt: 40 } })
c) Text Search
(Requires text index)
db.articles.find({ $text: { $search: "mongodb query api" } })
Options:
-
$search: "mongodb -nosql"
→ exclude words -
$language: "en"
→ set language -
$caseSensitive: true
d) Regex Search
db.users.find({ name: { $regex: /^A/i } })
Finds names starting with "A", case-insensitive.
e) Array Search
db.orders.find({ items: { $all: ["pen", "notebook"] } })
4. Checking Index Usage
You can analyze query performance with .explain()
:
db.users.find({ name: "Alice" }).explain("executionStats")
-
Shows whether MongoDB used an index scan (IXSCAN) or a collection scan (COLLSCAN).
5. Listing and Dropping Indexes
-
List indexes:
db.users.getIndexes()
-
Drop one index:
db.users.dropIndex({ name: 1 })
-
Drop all indexes:
db.users.dropIndexes()
Summary
-
Indexes speed up searching in MongoDB.
-
Types of indexes: single-field, compound, unique, text, geospatial, TTL.
-
Searching can use equality, range, regex, arrays, text search.
-
Always check with
.explain()
to confirm index usage.