Skip to main content

Command Palette

Search for a command to run...

MongoDB Beginner’s Cheatsheet

Updated
3 min read
MongoDB Beginner’s Cheatsheet

MongoDB is a popular NoSQL database designed for speed, scalability, and flexibility. Instead of rows and tables, MongoDB stores data in documents (JSON-like objects) inside collections.

This cheatsheet is your quick reference to MongoDB basics


1. Getting Started

Connect to MongoDB

mongo

Or using connection string:

mongo "mongodb://localhost:27017"

2. Databases

Show databases

show dbs

Create/Use a database

use myDatabase

Show current database

db

3. Collections

Show collections

show collections

Create collection

db.createCollection("users")

4. Insert Documents

Insert one

db.users.insertOne({ name: "Alice", age: 22 })

Insert many

db.users.insertMany([
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 30 }
])

5. Query Documents

Find all

db.users.find()

Find with condition

db.users.find({ age: 25 })

Find with projection (select fields)

db.users.find({ age: 25 }, { name: 1, _id: 0 })

6. Update Documents

Update one

db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 23 } }
)

Update many

db.users.updateMany(
  { age: { $gte: 25 } },
  { $set: { status: "Active" } }
)

7. Delete Documents

Delete one

db.users.deleteOne({ name: "Charlie" })

Delete many

db.users.deleteMany({ age: { $lt: 20 } })

8. Common Operators

  • $eq → equal to

  • $ne → not equal

  • $gt → greater than

  • $gte → greater than or equal

  • $lt → less than

  • $lte → less than or equal

  • $in → in array

  • $nin → not in array

Example:

db.users.find({ age: { $gt: 20, $lt: 30 } })

9. Sorting & Limiting

Sort results

db.users.find().sort({ age: -1 }) // descending

Limit results

db.users.find().limit(5)

10. Indexes

Create index

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

Show indexes

db.users.getIndexes()

11. Aggregation (Quick Example)

db.users.aggregate([
  { $match: { age: { $gte: 18 } } },
  { $group: { _id: "$status", count: { $sum: 1 } } }
])

12. Backup & Restore

Export collection

mongoexport --db=myDatabase --collection=users --out=users.json

Import collection

mongoimport --db=myDatabase --collection=users --file=users.json

Final Notes

  • MongoDB stores data in BSON (binary JSON).

  • Collections ≈ tables, Documents ≈ rows.

  • Flexible schema → no strict column definitions.

  • Great for scalable apps, analytics, and real-time apps.


Save this cheatsheet for quick reference.
If you’re just starting out, play with simple inserts and queries before diving into aggregation pipelines and indexes.