MongoDB 8 cheatsheet
MongoDB 8: Indexes and performance
7 common MongoDB 8 tasks.
Create a unique index
Reject documents with a duplicate value.
db.users.createIndex({ email: 1 }, { unique: true })
Create a compound index
Index two fields together, in the order you filter and sort by them.
db.orders.createIndex({ userId: 1, createdAt: -1 })
Expire documents automatically
Delete documents an hour after the time in createdAt.
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
See how a query runs
Show the plan, index use and documents examined.
db.users.find({ email: "[email protected]" }).explain("executionStats")