Junior — Middle
Describe how you improved query efficiency in MongoDB
sobes.tech AI
Answer from AI
To improve query efficiency in MongoDB, I used several approaches:
-
Indexing — creating indexes on fields that are frequently used in filtering and sorting. This significantly speeds up searches.
-
Projection — selecting only the necessary fields in the query to reduce the amount of data transmitted.
-
Aggregation — using aggregate functions and pipelines to process data on the database side, which reduces the load on the application.
-
Query optimization — analyzing queries with
explain()to identify bottlenecks. -
Sharding — distributing collections across multiple servers for large data volumes.
An example of a simple query with projection and index in Python using PyMongo:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client.mydb
# Create an index on the 'user_id' field
db.orders.create_index('user_id')
# Query with filter and projection
cursor = db.orders.find({'user_id': 12345}, {'_id': 0, 'order_date': 1, 'total': 1})
for doc in cursor:
print(doc)