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.
On this page
Connect & Explore #
| Command | Action |
|---|---|
| Connect to localhost:27017 | |
| Connect with credentials | |
| MongoDB Atlas | |
show dbs | List databases |
use app | Switch to (or create) a database |
db | Current database |
show collections | List collections |
db.users.countDocuments() | Count documents |
db.dropDatabase() | Delete the current database ⚠ |
exit | Quit |
Create #
db.users.insertOne({ name: "Milan", city: "Antwerp", roles: ["admin"], createdAt: new Date() })
db.users.insertMany([{ name: "Lisa" }, { name: "Dennis" }])
Read #
| Command | Action |
|---|---|
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 #
| Operator | Example |
|---|---|
$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 #
| Command | Action |
|---|---|
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 #
| Command | Action |
|---|---|
db.users.deleteOne({ name: "Lisa" }) | Delete the first match |
db.users.deleteMany({ active: false }) | Delete all matches |
db.users.drop() | Delete the collection ⚠ |
Indexes #
| Command | Action |
|---|---|
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) #
| Command | Action |
|---|---|
| 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" }).
mongoshMongoDB shell. mongosh [options] [connection-string]
| Option | What it does |
|---|---|
"mongodb://localhost:27017/app" | Connect with a URL |
"mongodb+srv://cluster.x.mongodb.net/app" | MongoDB Atlas |
--username milan (-u) | User (-p asks for the password) |
--authenticationDatabase admin | Where the user is defined |
--host / --port | Host / port |
--eval "db.users.countDocuments()" | Run code and exit |
--file script.js (-f) | Run a script |
--quiet | No banner |
--json=relaxed | JSON output with --eval |
--tls | Encrypted connection |
--nodb | Start without connecting |
mongodumpBack up MongoDB (BSON files). mongodump [options]
| Option | What it does |
|---|---|
--uri "mongodb://…" | Connection string |
--db app (-d) | One database |
--collection users (-c) | One collection |
--out ./backup (-o) | Output folder |
--archive=backup.gz --gzip | One compressed file |
--query '{"active":true}' | Only matching documents |
--excludeCollection logs | Skip a collection |
--oplog | Point-in-time snapshot (replica sets) |
mongorestoreRestore a mongodump backup. mongorestore [options] [folder]
| Option | What it does |
|---|---|
--uri "mongodb://…" | Connection string |
./backup | Folder to restore |
--archive=backup.gz --gzip | From one compressed file |
--drop | Drop collections before restoring |
--nsInclude "app.*" | Only some namespaces |
--nsFrom "app.*" --nsTo "test.*" | Restore into another database |
--dryRun | Show what would happen |
mongoexportExport a collection to JSON or CSV. mongoexport [options]
| Option | What it does |
|---|---|
--uri / --db app | Connection / database |
--collection users (-c) | Collection |
--out users.json (-o) | Output file |
--jsonArray | One JSON array instead of one document per line |
--type=csv --fields name,email | CSV with these columns |
--query '{"active":true}' (-q) | Filter |
--sort '{"name":1}' / --limit 100 | Sort / limit |
--pretty | Indented JSON |
mongoimportImport JSON, CSV or TSV into a collection. mongoimport [options] --file file
| Option | What it does |
|---|---|
--uri / --db app | Connection / database |
--collection users (-c) | Collection |
--file users.json | Input file |
--jsonArray | The file is one JSON array |
--type=csv --headerline | CSV with column names in the first row |
--drop | Empty the collection first |
--mode upsert | Update existing documents (--upsertFields email) |
Nothing on this sheet matches “”.