MongoDB

Document database with flexible schemas - store JSON-like data, scale horizontally, query with ease

TL;DR

What: A document-oriented NoSQL database using JSON-like documents.

Why: Flexible schema, horizontal scaling, great for rapid development.

Quick Start

Install:

macOS:

brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community

Docker:

docker run --name mongo -p 27017:27017 -d mongo

Connect:

mongosh

Or use MongoDB Atlas (cloud): mongodb.com/atlas

Basic operations:

use myapp
db.users.insertOne({ name: "John", email: "[email protected]" })
db.users.find()

Cheatsheet

CommandDescription
show dbsList databases
use dbnameSwitch database
show collectionsList collections
db.col.insertOne({})Insert document
db.col.find()Find all documents
db.col.findOne({})Find one document
db.col.updateOne({}, {$set: {}})Update document
db.col.deleteOne({})Delete document

Gotchas

CRUD operations

// Insert
db.users.insertOne({ name: "John", email: "[email protected]" })
db.users.insertMany([{ name: "Jane" }, { name: "Bob" }])

// Find
db.users.find({ name: "John" })
db.users.find({ age: { $gt: 18 } })
db.users.find().limit(10).sort({ created: -1 })

// Update
db.users.updateOne(
  { email: "[email protected]" },
  { $set: { name: "Johnny" } }
)

// Delete
db.users.deleteOne({ email: "[email protected]" })

Query operators

// Comparison
{ age: { $gt: 18 } }    // greater than
{ age: { $gte: 18 } }   // greater than or equal
{ age: { $lt: 30 } }    // less than
{ age: { $in: [18, 21, 25] } }  // in array

// Logical
{ $and: [{ age: { $gt: 18 } }, { active: true }] }
{ $or: [{ name: "John" }, { name: "Jane" }] }

Indexes

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

Aggregation

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$userId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } }
])

Next Steps