00:00

MongoDB Commands Cheat Sheet

Last updated:

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

Terminal
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

CommandWhat it does
helpLists shell commands; db.help() and db.books.help() show methods
show dbsLists databases that contain data
use bookstoreSwitches to a database (created on first write)
dbShows the current database
show collectionsLists collections in the current database
show users / show rolesLists users and roles of the current database
itShows the next batch of cursor results
clsClears the screen
load("file.js")Runs a JavaScript file in the current session
exit or quit()Leaves the shell

3. Database Commands

mongosh
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

mongosh
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

mongosh
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

mongosh
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

GroupOperators
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

mongosh
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

GroupOperators
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

mongosh
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

mongosh
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 stagesPurpose
$match, $project, $addFields / $setFilter and reshape documents
$group, $bucket, $count, $facetSummarize
$sort, $limit, $skipOrder and page
$unwind, $lookup, $unionWithArrays and joins
$out, $mergeWrite results to a collection

12. Index Commands

mongosh
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

mongosh
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

mongosh
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

mongosh
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

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

mongosh
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

ToolExamplePurpose
mongodumpmongodump --uri="$URI" --gzip --archive=backup.gzBinary backup
mongorestoremongorestore --uri="$URI" --gzip --archive=backup.gzRestore a backup
mongoexportmongoexport --uri="$URI" -c books --type=csv --fields=title,price -o books.csvExport JSON or CSV
mongoimportmongoimport --uri="$URI" -c books --file=books.json --jsonArrayImport JSON, CSV or TSV
mongostatmongostat --uri="$URI" 5Live server statistics
mongotopmongotop --uri="$URI" 10Time spent reading and writing per collection

More: Backup and Restore.