Back to Blog
Tutorial7 min read2026-05-01

MongoDB Getting Started: NoSQL for Web Developers

Get up and running with MongoDB in this hands-on tutorial covering documents, collections, CRUD operations, aggregation, and indexing.

Ajay Kumar
Ajay Kumar
Founder & DevOps, PandaStack

What Is MongoDB?

MongoDB is a document-oriented NoSQL database. Instead of rows in tables, it stores documents — JSON-like objects that can have nested fields and arrays. This makes it a natural fit for applications where data shapes vary, where you need to store hierarchical data, or where you're iterating quickly on a schema.

MongoDB shines for: content management systems, product catalogs, user activity feeds, real-time analytics, and applications with flexible or evolving schemas.

Connecting to MongoDB

# Connect with the mongo shell (mongosh)
mongosh "mongodb://your-host:27017/myapp"   --username myuser --password mypassword

Switch to your database:

use myapp

Creating Documents (Insert)

In MongoDB, collections are created automatically on first insert:

# Insert a single document
db.users.insertOne({
  name: "Alice",
  email: "alice@example.com",
  role: "admin",
  createdAt: new Date(),
  tags: ["early-adopter", "beta"]
})

# Insert multiple documents
db.users.insertMany([
  { name: "Bob",   email: "bob@example.com",   role: "member" },
  { name: "Carol", email: "carol@example.com", role: "member" }
])

Each document automatically gets an _id field (a unique ObjectId).

Reading Documents (Find)

# Find all documents
db.users.find()

# Find with a filter
db.users.find({ role: "admin" })

# Find with multiple conditions
db.users.find({ role: "member", createdAt: { $gt: new Date("2026-01-01") } })

# Return specific fields only (projection)
db.users.find({ role: "admin" }, { name: 1, email: 1, _id: 0 })

# Find one document
db.users.findOne({ email: "alice@example.com" })

# Sort and limit
db.users.find().sort({ createdAt: -1 }).limit(10)

Query Operators

# Comparison
db.products.find({ price: { $gte: 10, $lte: 100 } })
db.products.find({ category: { $in: ["electronics", "books"] } })

# Array contains
db.users.find({ tags: "beta" })

# Nested field
db.orders.find({ "shipping.country": "US" })

# Text search (requires text index)
db.posts.find({ $text: { $search: "mongodb performance" } })

Updating Documents

# Update a single document
db.users.updateOne(
  { email: "bob@example.com" },
  { $set: { role: "admin", updatedAt: new Date() } }
)

# Increment a numeric field
db.posts.updateOne(
  { _id: ObjectId("...") },
  { $inc: { viewCount: 1 } }
)

# Push to an array
db.users.updateOne(
  { email: "alice@example.com" },
  { $push: { tags: "power-user" } }
)

# Update many documents
db.users.updateMany(
  { role: "member" },
  { $set: { emailVerified: false } }
)

# Upsert — insert if not found
db.settings.updateOne(
  { key: "theme" },
  { $set: { value: "dark" } },
  { upsert: true }
)

Deleting Documents

# Delete one
db.users.deleteOne({ email: "carol@example.com" })

# Delete many
db.sessions.deleteMany({ expiresAt: { $lt: new Date() } })

Aggregation Pipeline

The aggregation pipeline is MongoDB's equivalent of SQL's GROUP BY, JOIN, and window functions:

# Count orders by status
db.orders.aggregate([
  { $group: { _id: "$status", count: { $sum: 1 }, total: { $sum: "$amount" } } },
  { $sort: { count: -1 } }
])

# Join users to their orders (like SQL JOIN)
db.orders.aggregate([
  { $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "user"
  }},
  { $unwind: "$user" },
  { $project: { "user.name": 1, amount: 1, status: 1 } }
])

# Filter, group, and sort in a pipeline
db.orders.aggregate([
  { $match: { status: "completed", createdAt: { $gte: new Date("2026-01-01") } } },
  { $group: { _id: "$userId", totalSpent: { $sum: "$amount" } } },
  { $sort: { totalSpent: -1 } },
  { $limit: 10 }
])

Indexing in MongoDB

# Single-field index
db.users.createIndex({ email: 1 })

# Unique index
db.users.createIndex({ email: 1 }, { unique: true })

# Compound index
db.orders.createIndex({ userId: 1, createdAt: -1 })

# Text index for full-text search
db.posts.createIndex({ title: "text", body: "text" })

# List all indexes
db.orders.getIndexes()

# Explain a query
db.users.find({ email: "alice@example.com" }).explain("executionStats")

Schema Design Tips

  • Embed related data that is always read together (e.g., order line items inside an order document)
  • Reference data that is large, shared across documents, or updated frequently (e.g., user profiles referenced by userId)
  • Avoid unbounded arrays — if an array can grow to thousands of items, store as a separate collection
  • Use consistent field names and types across documents in a collection

Running MongoDB Alongside PandaStack

PandaStack's managed database lineup covers PostgreSQL, MySQL, and Redis — MongoDB is not offered as a managed engine. If your application needs a document store, run it with a provider such as MongoDB Atlas and connect to it from your PandaStack services via an environment variable, the same way you would wire up any external dependency.

If your documents are only moderately nested, PostgreSQL's JSONB columns are often a simpler fit and can be provisioned directly from the Databases panel.

Documentation: [docs.pandastack.io](https://docs.pandastack.io).

Summary

OperationCommand
InsertinsertOne / insertMany
Readfind / findOne
UpdateupdateOne / updateMany
DeletedeleteOne / deleteMany
Aggregateaggregate with pipeline stages
IndexcreateIndex

MongoDB's flexible document model and powerful aggregation pipeline make it a strong choice for many web application use cases — especially when your data naturally fits a document structure.

Ready to deploy?

Start free on PandaStack.

Start free on PandaStack

More in Tutorial

Browse all Tutorial articles →

See also