MongoDB 8 cheatsheet

MongoDB 8: Indexes and performance

7 common MongoDB 8 tasks.

Create an index

Create an ascending index on one field.

db.users.createIndex({ email: 1 })

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 })

List indexes

Show the indexes on a collection.

db.users.getIndexes()

See how a query runs

Show the plan, index use and documents examined.

db.users.find({ email: "[email protected]" }).explain("executionStats")

See running operations

List operations that are in progress.

db.currentOp()

Was this page helpful?