MongoDB Commands Cheat Sheet
This page is a practical reference of the MongoDB commands you will use most often in mongosh, the MongoDB Shell. Each section groups related commands with a short example, so you can find what you need quickly. Links point to the full tutorials for each topic.
All commands were written for MongoDB 8.0 and mongosh. The old
mongo shell was removed in MongoDB 6.0; use mongosh instead.1. Connecting with mongosh
mongosh # localhost:27017
mongosh "mongodb://localhost:27017/bookstore" # open a specific database
mongosh "mongodb://user@db1:27017,db2:27017/?replicaSet=rs0&authSource=admin"
mongosh "mongodb+srv://user@cluster0.abcde.mongodb.net/bookstore" # MongoDB Atlas
mongosh --quiet --eval 'db.version()' # run one command and exit
mongosh script.js # run a script file
2. Shell Helpers
| Command | What it does |
|---|---|
help | Lists shell commands; db.help() and db.books.help() show methods |
show dbs | Lists databases that contain data |
use bookstore | Switches to a database (created on first write) |
db | Shows the current database |
show collections | Lists collections in the current database |
show users / show roles | Lists users and roles of the current database |
it | Shows the next batch of cursor results |
cls | Clears the screen |
load("file.js") | Runs a JavaScript file in the current session |
exit or quit() | Leaves the shell |
3. Database Commands
use bookstore // switch / create
db.getName() // current database name
db.stats() // size and counts
db.getSiblingDB("reports") // another database without switching
db.dropDatabase() // delete the current database
db.version() // server version
More: Create Database, Drop Database.
4. Collection Commands
db.createCollection("books")
db.createCollection("logs", { capped: true, size: 10485760 })
db.createCollection("metrics", { timeseries: { timeField: "ts", metaField: "host" } })
db.createView("cheapBooks", "books", [ { $match: { price: { $lt: 500 } } } ])
db.getCollectionNames()
db.getCollectionInfos({ name: "books" })
db.books.renameCollection("titles")
db.books.stats()
db.books.drop()
5. Insert Documents
db.books.insertOne({ title: "Practical Java Streams", price: 499 })
db.books.insertMany([ { title: "A" }, { title: "B" } ], { ordered: false })
db.books.bulkWrite([
{ insertOne: { document: { title: "C" } } },
{ updateOne: { filter: { title: "A" }, update: { $set: { price: 300 } } } },
{ deleteOne: { filter: { title: "B" } } }
])
6. Query Documents
db.books.find() // all
db.books.find({ category: "Java" }) // equality
db.books.find({ price: { $gte: 400, $lte: 600 } }) // range
db.books.find({ "publisher.country": "IN" }) // embedded field
db.books.find({ tags: { $all: ["java", "spring"] } }) // array contains both
db.books.find({}, { title: 1, _id: 0 }) // projection
db.books.find().sort({ price: -1 }).skip(10).limit(10) // sort and page
db.books.findOne({ _id: 1 })
db.books.countDocuments({ category: "Java" })
db.books.estimatedDocumentCount()
db.books.distinct("category")
7. Query Operators
| Group | Operators |
|---|---|
| Comparison | $eq $ne $gt $gte $lt $lte $in $nin |
| Logical | $and $or $not $nor |
| Element | $exists $type |
| Array | $all $elemMatch $size |
| Evaluation | $regex $expr $mod $text $jsonSchema |
| Geospatial | $near $geoWithin $geoIntersects |
More: Query Document.
8. Update Documents
db.books.updateOne({ _id: 1 }, { $set: { price: 459 } })
db.books.updateMany({ stock: 0 }, { $set: { available: false } })
db.books.updateOne({ _id: 1 }, { $inc: { stock: -1 } })
db.books.updateOne({ _id: 1 }, { $push: { tags: "lambdas" } })
db.books.updateOne({ isbn: "978-1" }, { $set: { title: "New" } }, { upsert: true })
db.books.replaceOne({ _id: 3 }, { title: "Replaced", price: 400 })
db.books.findOneAndUpdate({ _id: 1 }, { $inc: { views: 1 } }, { returnDocument: "after" })
9. Update Operators
| Group | Operators |
|---|---|
| Fields | $set $unset $inc $mul $min $max $rename $currentDate $setOnInsert |
| Arrays | $push $addToSet $pull $pullAll $pop |
| Modifiers | $each $sort $slice $position |
| Positional | $ $[] $[<identifier>] with arrayFilters |
More: Update Document.
10. Delete Documents
db.orders.deleteOne({ _id: 3 })
db.orders.deleteMany({ status: "CANCELLED" })
db.orders.deleteMany({}) // all documents, keeps indexes
db.queue.findOneAndDelete({}, { sort: { priority: -1 } })
11. Aggregation
db.orders.aggregate([
{ $match: { status: "SHIPPED" } }, // filter
{ $unwind: "$items" }, // one document per array element
{ $lookup: { from: "books", localField: "items.bookId", // join
foreignField: "_id", as: "book" } },
{ $group: { _id: "$customerId", spent: { $sum: "$total" }, orders: { $sum: 1 } } },
{ $sort: { spent: -1 } },
{ $limit: 5 },
{ $project: { _id: 0, customer: "$_id", spent: 1, orders: 1 } }
])
| Common stages | Purpose |
|---|---|
$match, $project, $addFields / $set | Filter and reshape documents |
$group, $bucket, $count, $facet | Summarize |
$sort, $limit, $skip | Order and page |
$unwind, $lookup, $unionWith | Arrays and joins |
$out, $merge | Write results to a collection |
12. Index Commands
db.books.createIndex({ category: 1, price: -1 })
db.users.createIndex({ email: 1 }, { unique: true })
db.sessions.createIndex({ lastSeen: 1 }, { expireAfterSeconds: 1800 })
db.books.getIndexes()
db.books.hideIndex("category_1_price_-1")
db.books.dropIndex("category_1_price_-1")
db.books.find({ category: "Java" }).explain("executionStats")
db.books.aggregate([{ $indexStats: {} }])
More: Indexing.
13. Transactions
const s = db.getMongo().startSession()
s.withTransaction(() => {
const bank = s.getDatabase("bank")
bank.accounts.updateOne({ _id: "A" }, { $inc: { balance: -100 } })
bank.accounts.updateOne({ _id: "B" }, { $inc: { balance: 100 } })
})
s.endSession()
14. Users and Roles
use admin
db.createUser({ user: "appUser", pwd: passwordPrompt(), roles: [ { role: "readWrite", db: "bookstore" } ] })
db.grantRolesToUser("appUser", [ { role: "read", db: "reports" } ])
db.revokeRolesFromUser("appUser", [ { role: "read", db: "reports" } ])
db.changeUserPassword("appUser", passwordPrompt())
db.getUsers()
db.dropUser("appUser")
db.auth("appUser", passwordPrompt()) // authenticate in an open session
15. Server Administration
db.serverStatus() // overall server metrics
db.currentOp({ secs_running: { $gte: 5 } }) // operations running longer than 5 s
db.killOp(12345) // stop an operation by its opid
db.setProfilingLevel(1, { slowms: 100 }) // log operations slower than 100 ms
db.system.profile.find().sort({ ts: -1 }).limit(5) // latest profiled operations
db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 })
db.fsyncLock(); db.fsyncUnlock() // pause / resume writes (snapshots)
db.shutdownServer() // from the admin database
16. Replica Set Commands
rs.initiate({ _id: "rs0", members: [ { _id: 0, host: "db1:27017" }, { _id: 1, host: "db2:27017" }, { _id: 2, host: "db3:27017" } ] })
rs.status()
rs.conf()
rs.add("db4:27017")
rs.remove("db4:27017")
rs.stepDown(60)
rs.printReplicationInfo()
rs.printSecondaryReplicationInfo()
db.hello()
More: Replication.
17. Sharding Commands (via mongos)
sh.status()
sh.addShard("rs1/db5:27017,db6:27017,db7:27017")
sh.shardCollection("shop.orders", { customerId: "hashed" })
sh.getBalancerState()
db.adminCommand({ reshardCollection: "shop.orders", key: { region: 1, customerId: 1 } })
18. Command-Line Tools
| Tool | Example | Purpose |
|---|---|---|
mongodump | mongodump --uri="$URI" --gzip --archive=backup.gz | Binary backup |
mongorestore | mongorestore --uri="$URI" --gzip --archive=backup.gz | Restore a backup |
mongoexport | mongoexport --uri="$URI" -c books --type=csv --fields=title,price -o books.csv | Export JSON or CSV |
mongoimport | mongoimport --uri="$URI" -c books --file=books.json --jsonArray | Import JSON, CSV or TSV |
mongostat | mongostat --uri="$URI" 5 | Live server statistics |
mongotop | mongotop --uri="$URI" 10 | Time spent reading and writing per collection |
More: Backup and Restore.
Was this tutorial helpful?