In this chapter, we explore advanced database operations in MongoDB:
- Indexes → Make queries faster
- Queries → Filter data with conditions
- Aggregations → Process and transform data
An index is like an index in a book:
Instead of reading every page, MongoDB looks up the index to quickly find documents.
coll.create_index("name")Now queries using name will be much faster.
Queries allow filtering results.
# Find students with age > 20
coll.find({"age": {"$gt": 20}})
# Find students in Kolkata
coll.find({"city": "Kolkata"})Aggregation pipelines allow grouping, filtering, and calculating over data.
pipeline = [
{"$group": {"_id": "$city", "total": {"$sum": 1}}},
{"$sort": {"total": -1}}
]
coll.aggregate(pipeline)[Collection] ---> [Match/Filter] ---> [Group] ---> [Sort] ---> [Result]
Example:
Students ---> age > 20 ---> group by city ---> sort desc ---> Report
- Indexes = Faster queries
- Queries = Fetch filtered data
- Aggregations = Data analysis inside MongoDB