🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

MongoDB Complete Guide 2026: CRUD, Aggregation and Production Patterns

⏱️4 min read  ·  749 words

MongoDB is the world’s most popular NoSQL database. In 2026, MongoDB 8.0 brings major performance improvements and better developer tools. This complete guide covers everything from your first document to production-grade MongoDB architecture.

Why MongoDB?

  • Flexible schema — no migrations for evolving data models
  • JSON-like documents — natural fit for JavaScript/Python APIs
  • Horizontal scaling — built-in sharding for massive data
  • Rich query language — aggregation pipelines rival SQL for analytics
  • Atlas Vector Search — semantic search for AI applications

Installation

# macOS
brew tap mongodb/brew && brew install mongodb-community@8.0
brew services start mongodb-community@8.0

# Ubuntu 24.04
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
sudo apt update && sudo apt install -y mongodb-org
sudo systemctl start mongod

# Connect to shell
mongosh

Core CRUD Operations

// Switch database
use techpulse_db

// INSERT
db.users.insertOne({
  name: "Alice",
  email: "alice@example.com",
  skills: ["Python", "React"],
  createdAt: new Date()
})

db.posts.insertMany([
  { title: "React Guide", views: 1500, tags: ["react", "js"] },
  { title: "Python Guide", views: 2300, tags: ["python", "backend"] }
])

// FIND
db.users.find({ skills: "Python" })     // match array element
db.posts.find(
  { views: { $gt: 1000 } },            // filter
  { title: 1, views: 1, _id: 0 }       // projection
)

// UPDATE
db.users.updateOne(
  { email: "alice@example.com" },
  { $set: { role: "senior" }, $push: { skills: "Go" } }
)
db.posts.updateMany(
  { tags: "python" },
  { $inc: { views: 100 } }
)

// DELETE
db.users.deleteOne({ email: "alice@example.com" })

Indexes for Performance

// Check slow queries
db.posts.find({ title: "React Guide" }).explain("executionStats")

// Create indexes
db.users.createIndex({ email: 1 }, { unique: true })
db.posts.createIndex({ tags: 1, views: -1 })       // compound
db.articles.createIndex({ title: "text" })           // full-text search
db.events.createIndex({ createdAt: 1 },
  { expireAfterSeconds: 2592000 })                    // TTL: 30 days

// Always create indexes before going to production
db.users.getIndexes()

Aggregation Pipeline

// Sales report: revenue by category
db.orders.aggregate([
  { $match: { status: "completed", createdAt: { $gte: new Date("2026-01-01") } } },
  { $unwind: "$items" },
  { $group: {
    _id: "$items.category",
    totalRevenue: { $sum: { $multiply: ["$items.price", "$items.qty"] } },
    count: { $sum: 1 }
  }},
  { $sort: { totalRevenue: -1 } },
  { $limit: 10 },
  { $project: { category: "$_id", revenue: { $round: ["$totalRevenue", 2] }, _id: 0 }}
])

Python with PyMongo and Motor (Async)

from pymongo import MongoClient, ASCENDING
from datetime import datetime

# Sync
client = MongoClient("mongodb://localhost:27017/")
db = client.techpulse_db
users = db.users

result = users.insert_one({"name": "Alice", "createdAt": datetime.utcnow()})
alice = users.find_one({"name": "Alice"}, {"_id": 0})
users.update_one({"name": "Alice"}, {"$set": {"active": True}})

# Async with Motor (for FastAPI)
import motor.motor_asyncio

async_client = motor.motor_asyncio.AsyncIOMotorClient("mongodb://localhost:27017")
async_db = async_client.techpulse_db

async def create_user(data: dict) -> str:
    result = await async_db.users.insert_one(data)
    return str(result.inserted_id)

async def list_users(page: int = 1) -> list:
    cursor = async_db.users.find().skip((page-1)*20).limit(20)
    return await cursor.to_list(length=20)

Data Modeling: Embed vs Reference

// Embed when reading together (1-to-few)
{
  _id: ObjectId("..."),
  title: "MongoDB Guide",
  author: { name: "Alice", email: "alice@blog.com" },  // embedded
  tags: ["mongodb", "nosql"]                            // embedded
}

// Reference when shared/large (1-to-many)
// posts: { authorId: ObjectId("user1") }
// Look up with $lookup
db.posts.aggregate([
  { $lookup: {
    from: "users",
    localField: "authorId",
    foreignField: "_id",
    as: "author"
  }},
  { $unwind: "$author" }
])

Production Best Practices

  • Use replica sets — minimum 3 nodes for HA
  • Enable auth — never run MongoDB without authentication
  • Validate documents — use JSON Schema or Pydantic
  • Monitor slow queries — enable profiler, use Atlas monitoring
  • Limit document size — stay well under 16MB BSON limit
  • Atlas for production — managed service with backups, scaling, monitoring

# Atlas connection
MONGO_URI = "mongodb+srv://user:pass@cluster.mongodb.net/mydb?retryWrites=true&w=majority"
client = MongoClient(MONGO_URI)

MongoDB 8.0 in 2026 is the best document database for flexible, fast applications. Start simple, create proper indexes, and use the aggregation pipeline for analytics. Pair with Atlas Vector Search for AI-powered semantic search in your apps.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇬🇧 English🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা