Cheat Sheet Library

MongoDB Shell Cheat Sheet

MongoDB stores JSON-like documents in collections. mongosh is the modern shell. In examples, db.users means the collection users in the current database.

  • 49 entries
  • 11 sections
  • Updated
  • Click a command to see all its options

49 entries

On this page

Connect & Explore #

CommandAction
Connect to localhost:27017
Connect with credentials
MongoDB Atlas
show dbsList databases
use appSwitch to (or create) a database
dbCurrent database
show collectionsList collections
db.users.countDocuments()Count documents
db.dropDatabase()Delete the current database ⚠
exitQuit

Create #

db.users.insertOne({ name: "Milan", city: "Antwerp", roles: ["admin"], createdAt: new Date() })
db.users.insertMany([{ name: "Lisa" }, { name: "Dennis" }])

Read #

CommandAction
db.users.find()All documents (type it for more)
db.users.findOne({ name: "Milan" })First match
db.users.find({ city: "Antwerp" })Filter
db.users.find({}, { name: 1, _id: 0 })Projection: only some fields
.sort({ createdAt: -1 })Sort (1 = asc, -1 = desc)
.limit(10).skip(20)Paging
db.users.distinct("city")Unique values
db.users.find({ _id: ObjectId("6650...") })By id
db.users.find({ "address.city": "Gent" })Nested field (use quotes)

Query Operators #

OperatorExample
$eq $ne{ status: { $ne: "done" } }
$gt $gte $lt $lte{ age: { $gte: 18, $lt: 65 } }
$in / $nin{ city: { $in: ["Antwerp", "Gent"] } }
$and / $or{ $or: [{ city: "Gent" }, { age: { $lt: 25 } }] }
$exists{ email: { $exists: true } }
$regex{ name: { $regex: "^mi", $options: "i" } }
Array contains{ roles: "admin" }
$all / $size{ roles: { $all: ["admin", "dev"] } }
$elemMatch{ items: { $elemMatch: { qty: { $gt: 5 }, sku: "A1" } } }

Update #

CommandAction
db.users.updateOne({ name: "Milan" }, { $set: { city: "Gent" } })Set fields
db.users.updateMany({}, { $set: { active: true } })Update all
{ $unset: { temp: "" } }Remove a field
{ $inc: { logins: 1 } }Increment
{ $push: { roles: "dev" } } / { $addToSet: ... }Add to an array / add if missing
{ $pull: { roles: "dev" } }Remove from an array
updateOne(filter, update, { upsert: true })Insert if nothing matches
db.users.findOneAndUpdate(filter, update, { returnDocument: "after" })Update and return the new doc
db.users.replaceOne(filter, newDoc)Replace the whole document

Delete #

CommandAction
db.users.deleteOne({ name: "Lisa" })Delete the first match
db.users.deleteMany({ active: false })Delete all matches
db.users.drop()Delete the collection ⚠

Indexes #

CommandAction
db.users.createIndex({ email: 1 }, { unique: true })Unique index
db.users.createIndex({ city: 1, createdAt: -1 })Compound index
db.users.getIndexes()List indexes
db.users.dropIndex("email_1")Remove
db.users.find({ email: "x" }).explain("executionStats")Check whether an index is used

Aggregation #

db.orders.aggregate([
  { $match: { status: "paid" } },                                  // filter
  { $group: { _id: "$customerId", total: { $sum: "$amount" }, n: { $sum: 1 } } },
  { $sort: { total: -1 } },
  { $limit: 5 },
  { $lookup: { from: "users", localField: "_id", foreignField: "_id", as: "user" } },  // join
  { $unwind: "$user" },
  { $project: { _id: 0, name: "$user.name", total: 1, n: 1 } }
])

Users #

use admin
db.createUser({ user: "app", pwd: passwordPrompt(), roles: [{ role: "readWrite", db: "app" }] })

Backup & Import (terminal, not mongosh) #

CommandAction
Back up
Restore
Export JSON
Import a JSON array

Tips #

  • MongoDB Compass is a free GUI for browsing data and building queries visually.
  • In Node.js the same queries work through the driver or Mongoose: await User.find({ city: "Antwerp" }).