🏠 Portal

MongoDB

Learn MongoDB basics including CRUD operations, indexing, and aggregation using modern MongoDB 6.x features.

1. What is MongoDB?

MongoDB is a NoSQL, document-oriented database that stores data as BSON (binary JSON). Collections hold documents, similar to how tables hold rows in SQL.

Tip: Use mongosh (MongoDB Shell) to run these commands interactively.

2. Starting MongoDB and Connecting

# START the MongoDB service
mongod --dbpath /data/db

# Connect USING Mongo Shell
mongosh

# CHECK the CURRENT DATABASE
> db

3. Creating and Using Databases

# Switch OR CREATE a NEW DATABASE
> USE shop

# SHOW ALL DATABASES
> SHOW dbs

4. Inserting Documents

# INSERT a single document
> db.products.insertOne({ name: "Laptop", price: 1200, tags: ["electronics", "sale"] })

# INSERT multiple documents
> db.products.insertMany([
  { name: "Phone", price: 800, specs: { color: "black", memory: "128GB" } },
  { name: "Tablet", price: 600, specs: { color: "white", memory: "256GB" } }
])

5. Querying Documents

# RETURN ALL documents
> db.products.find()

# Find WITH a filter
> db.products.find({ price: { $gt: 700 } })

# Project specific fields
> db.products.find({}, { name: 1, price: 1 })

# Find USING nested field
> db.products.find({ "specs.memory": "128GB" })

6. Updating and Deleting Documents

# UPDATE one document
> db.products.updateOne(
  { name: "Phone" },
  { $SET: { price: 850, "specs.color": "blue" } }
)

# UPDATE many
> db.products.updateMany({ price: { $lt: 1000 } }, { $inc: { price: 50 } })

# DELETE a document
> db.products.deleteOne({ name: "Tablet" })

7. Indexing and Query Optimization

# CREATE an INDEX ON price
> db.products.createIndex({ price: 1 })

# CREATE a compound INDEX
> db.products.createIndex({ name: 1, price: -1 })

# VIEW indexes
> db.products.getIndexes()

8. Aggregation Pipeline

# Simple aggregation
> db.products.aggregate([
  { $match: { price: { $gt: 700 } } },
  { $GROUP: { _id: NULL, avgPrice: { $AVG: "$price" }, maxPrice: { $MAX: "$price" } } }
])

# Unwind arrays AND GROUP BY tag
> db.products.aggregate([
  { $unwind: "$tags" },
  { $GROUP: { _id: "$tags", COUNT: { $SUM: 1 } } }
])

For more examples, see MongoDB Aggregation Complete Examples.

9. Relationships and Embedded Documents

MongoDB encourages embedding related data when it makes sense. However, referencing via ObjectId is possible too:

# Example of embedding
> db.orders.insertOne({
  order_id: 1,
  customer: { name: "Alice", email: "alice@example.com" },
  items: [
    { product_id: ObjectId("..."), quantity: 2 },
    { product_id: ObjectId("..."), quantity: 1 }
  ]
})

10. Common MongoDB Operators

$eq, $ne, $gt, $gte, $lt, $lte
$IN, $nin
$AND, $OR, $NOT
$EXISTS, $type
$SET, $unset, $inc, $push, $pull
$regex, $TEXT, $search
$lookup (FOR joins), $project, $GROUP, $sort, $LIMIT

🏠 Portal | 🚀 Getting Started | 📝 SQL Cheat Sheet