Skip to main content

MongoDB

Use this cheat sheet for everyday MongoDB work: connecting to a database, creating collections, inserting documents, querying data, updating records, deleting records, indexes, backups, and common admin checks.

Connect

Open the MongoDB shell:

mongosh

Connect with a local URI:

mongosh "mongodb://127.0.0.1:27017"

Connect with MongoDB Atlas:

mongosh "mongodb+srv://username:password@cluster.mongodb.net/database"

Show current database:

db

Show databases:

show dbs

Switch database:

use app_database

Collections

Show collections:

show collections

Create a collection:

db.createCollection("users")

Drop a collection:

db.users.drop()

Insert Documents

Insert one document:

db.users.insertOne({
name: "Ali",
email: "ali@example.com",
role: "admin",
createdAt: new Date()
})

Insert many documents:

db.users.insertMany([
{ name: "Sara", email: "sara@example.com", role: "user" },
{ name: "Ahmed", email: "ahmed@example.com", role: "user" }
])

Find Documents

Find all:

db.users.find()

Pretty print:

db.users.find().pretty()

Find one:

db.users.findOne({ email: "ali@example.com" })

Find with condition:

db.users.find({ role: "admin" })

Find with selected fields:

db.users.find(
{ role: "user" },
{ name: 1, email: 1, _id: 0 }
)

Query Operators

Greater than:

db.orders.find({ total: { $gt: 100 } })

Less than:

db.orders.find({ total: { $lt: 100 } })

In list:

db.users.find({ role: { $in: ["admin", "manager"] } })

Not equal:

db.users.find({ role: { $ne: "guest" } })

Search text with regex:

db.users.find({ name: /ali/i })

Sort, Limit, Count

Sort ascending:

db.users.find().sort({ name: 1 })

Sort descending:

db.users.find().sort({ createdAt: -1 })

Limit results:

db.users.find().limit(10)

Skip results:

db.users.find().skip(10).limit(10)

Count documents:

db.users.countDocuments()

Count with filter:

db.users.countDocuments({ role: "admin" })

Update Documents

Update one:

db.users.updateOne(
{ email: "ali@example.com" },
{ $set: { role: "manager" } }
)

Update many:

db.users.updateMany(
{ role: "user" },
{ $set: { active: true } }
)

Increment a value:

db.orders.updateOne(
{ orderId: "ORD-1001" },
{ $inc: { total: 10 } }
)

Push into an array:

db.users.updateOne(
{ email: "ali@example.com" },
{ $push: { tags: "vip" } }
)

Remove from an array:

db.users.updateOne(
{ email: "ali@example.com" },
{ $pull: { tags: "vip" } }
)

Delete Documents

Delete one:

db.users.deleteOne({ email: "ali@example.com" })

Delete many:

db.users.deleteMany({ active: false })

Delete all documents in a collection:

db.users.deleteMany({})

Indexes

Show indexes:

db.users.getIndexes()

Create an index:

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

Create a unique index:

db.users.createIndex({ email: 1 }, { unique: true })

Create a compound index:

db.orders.createIndex({ userId: 1, createdAt: -1 })

Drop an index:

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

Aggregation

Group and count:

db.orders.aggregate([
{ $group: { _id: "$status", count: { $sum: 1 } } }
])

Filter then group:

db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$userId", total: { $sum: "$total" } } }
])

Sort aggregation result:

db.orders.aggregate([
{ $group: { _id: "$status", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])

Backup And Restore

Dump one database:

mongodump --db app_database --out ./backup

Restore one database:

mongorestore --db app_database ./backup/app_database

Dump with URI:

mongodump --uri="mongodb+srv://username:password@cluster.mongodb.net/app_database" --out ./backup

Restore with URI:

mongorestore --uri="mongodb+srv://username:password@cluster.mongodb.net/app_database" ./backup/app_database

Common Admin Checks

Show server status:

db.serverStatus()

Show database stats:

db.stats()

Show collection stats:

db.users.stats()

Check current operations:

db.currentOp()

Node.js Connection Example

import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI);

await client.connect();

const db = client.db("app_database");
const users = db.collection("users");

const user = await users.findOne({ email: "ali@example.com" });

Key Ideas

  • Database stores related collections.
  • Collection stores documents.
  • Document is JSON-like data.
  • Index improves query speed.
  • Aggregation processes and summarizes data.
  • Atlas is MongoDB's hosted cloud database.