MongoDB Cheatsheet

View saved

MongoDB stores JSON-like documents in collections. Shape data for your queries; index the fields you filter on.

Practice in mongosh first, then use an official driver from your application language.

Shell & structure

mongosh

Connect to a local or Atlas deployment.

mongosh "mongodb://127.0.0.1:27017"

use / show

Switch database context and list collections.

use learning
show collections
db

Document

Field/value pairs with an _id (ObjectId by default).

db.notes.insertOne({ title: "Hi", tags: ["intro"] })

Drop carefully

Remove a collection or the current database.

// db.notes.drop()
// db.dropDatabase()

CRUD

insertOne / insertMany

Add documents; collections are created on first write.

db.books.insertMany([
  { title: "A", year: 2024 },
  { title: "B", year: 2025 }
])

find / findOne

Query with a filter document. Operators like $gte live inside fields.

db.books.find({ year: { $gte: 2024 } })
db.books.findOne({ title: "A" })

Projection / sort / limit

Shape and page results.

db.books.find({}, { title: 1, _id: 0 }).sort({ year: -1 }).limit(10)

updateOne

Change fields with update operators such as $set and $inc.

db.books.updateOne(
  { title: "A" },
  { $set: { featured: true } }
)

deleteOne / deleteMany

Remove matching documents after verifying the filter.

db.books.deleteMany({ archive: true })

Indexes & aggregation

createIndex

Speed up filters and unique constraints.

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

getIndexes

List indexes on a collection.

db.books.getIndexes()

aggregate

Pipeline stages transform documents.

db.books.aggregate([
  { $match: { year: { $gte: 2020 } } },
  { $group: { _id: "$year", n: { $sum: 1 } } }
])

countDocuments

Count matches accurately.

db.books.countDocuments({ tags: "nosql" })

Drivers peek

Connection URI

Store credentials in env vars, not source control.

mongodb+srv://user:pass@cluster/db

Node.js

Official mongodb package.

import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();

Python

Use PyMongo with a single client per process.

from pymongo import MongoClient
client = MongoClient(os.environ["MONGODB_URI"])

Embed vs reference

Embed data loaded together; reference shared or unbounded data.

{ "title": "Book", "authorId": ObjectId("...") }

Comments

One comment per signed-in account. Comments are saved with this page’s URL.