DEV Community

Cover image for A Complete Guide to MongoDB for Developers (With Code Examples)
Farhad Rahimi Klie
Farhad Rahimi Klie

Posted on • Edited on

A Complete Guide to MongoDB for Developers (With Code Examples)

MongoDB is a document-oriented NoSQL database designed for high scalability, flexibility, and performance. It is widely used in modern web applications, microservices, real-time systems, analytics platforms, and large-scale distributed architectures.


1. What Is MongoDB?

MongoDB is a schema-less document database that stores data in BSON (Binary JSON) format.

Key Characteristics

  • No fixed schema
  • Stores data as documents (JSON-like)
  • Horizontal scalability (sharding)
  • High availability (replica sets)
  • Rich query language
  • Built-in aggregation framework

2. MongoDB Data Model

Hierarchy

MongoDB Server
 └── Database
     └── Collection
         └── Document
             └── Fields
Enter fullscreen mode Exit fullscreen mode

Example Document

{
  "_id": ObjectId("65a1f0c7e4b0a12f90e1c111"),
  "name": "Farhad",
  "age": 25,
  "skills": ["JavaScript", "MongoDB"],
  "isActive": true
}
Enter fullscreen mode Exit fullscreen mode

3. BSON Internals (How Data Is Stored)

MongoDB does not store JSON directly. It uses BSON.

BSON Advantages

  • Binary encoded
  • Faster parsing
  • Supports additional types

BSON Data Types

Type Example
String "text"
Int32 NumberInt(10)
Int64 NumberLong(100)
Double 10.5
Boolean true
Date ISODate()
ObjectId ObjectId()
Array []
Embedded Document {}
Null null

4. MongoDB Architecture (High-Level)

Core Components

  • mongod → database engine
  • mongos → query router (sharding)
  • Replica Set
  • Shards
  • Config Servers

5. mongod Internals

mongod is the main MongoDB server process.

Responsibilities

  • Query execution
  • Index management
  • Replication
  • Storage engine interaction

6. Storage Engine (WiredTiger)

MongoDB uses WiredTiger by default.

WiredTiger Features

  • Document-level locking
  • MVCC (Multi-Version Concurrency Control)
  • Compression
  • Journaling

Memory Model

  • Cache (RAM)
  • Disk persistence
  • Checkpoints

7. MongoDB Journaling (Durability)

MongoDB ensures durability using write-ahead logging.

Write → Journal → Memory → Disk
Enter fullscreen mode Exit fullscreen mode

Enable Journaling

mongod --journal
Enter fullscreen mode Exit fullscreen mode

8. Replica Sets (High Availability)

A replica set is a group of MongoDB servers maintaining the same data.

Roles

  • Primary
  • Secondary
  • Arbiter

Replica Set Diagram

Primary
  ├── Secondary
  ├── Secondary
  └── Arbiter
Enter fullscreen mode Exit fullscreen mode

Initialize Replica Set

rs.initiate()
Enter fullscreen mode Exit fullscreen mode

9. Sharding (Horizontal Scaling)

Sharding splits data across multiple machines.

Components

  • Shards
  • mongos
  • Config Servers

Enable Sharding

sh.enableSharding("mydb")
Enter fullscreen mode Exit fullscreen mode

Shard a Collection

sh.shardCollection("mydb.users", { userId: 1 })
Enter fullscreen mode Exit fullscreen mode

10. Databases & Collections

Create Database

use myDatabase
Enter fullscreen mode Exit fullscreen mode

Create Collection

db.createCollection("users")
Enter fullscreen mode Exit fullscreen mode

Capped Collection

db.createCollection("logs", { capped: true, size: 1024 })
Enter fullscreen mode Exit fullscreen mode

11. CRUD Operations (Full Syntax)


Insert Documents

insertOne

db.users.insertOne({
  name: "Ali",
  age: 30
})
Enter fullscreen mode Exit fullscreen mode

insertMany

db.users.insertMany([
  { name: "A", age: 20 },
  { name: "B", age: 25 }
])
Enter fullscreen mode Exit fullscreen mode

Read Documents

find

db.users.find()
Enter fullscreen mode Exit fullscreen mode

findOne

db.users.findOne({ name: "Ali" })
Enter fullscreen mode Exit fullscreen mode

Projection

db.users.find({}, { name: 1, _id: 0 })
Enter fullscreen mode Exit fullscreen mode

Query Operators

Comparison

db.users.find({ age: { $gt: 18 } })
Enter fullscreen mode Exit fullscreen mode
Operator Meaning
$eq equals
$ne not equal
$gt greater
$gte greater or equal
$lt less
$lte less or equal

Logical

db.users.find({
  $and: [{ age: { $gt: 18 } }, { isActive: true }]
})
Enter fullscreen mode Exit fullscreen mode
Operator Meaning
$and AND
$or OR
$not NOT
$nor NOR

Update Documents

updateOne

db.users.updateOne(
  { name: "Ali" },
  { $set: { age: 31 } }
)
Enter fullscreen mode Exit fullscreen mode

updateMany

db.users.updateMany(
  { isActive: false },
  { $set: { archived: true } }
)
Enter fullscreen mode Exit fullscreen mode

Operators

Operator Function
$set set value
$unset remove field
$inc increment
$push add to array
$pull remove from array

Delete Documents

deleteOne

db.users.deleteOne({ name: "Ali" })
Enter fullscreen mode Exit fullscreen mode

deleteMany

db.users.deleteMany({ age: { $lt: 18 } })
Enter fullscreen mode Exit fullscreen mode

12. Indexing (Performance)

Create Index

db.users.createIndex({ email: 1 })
Enter fullscreen mode Exit fullscreen mode

Compound Index

db.users.createIndex({ age: 1, name: 1 })
Enter fullscreen mode Exit fullscreen mode

Unique Index

db.users.createIndex({ email: 1 }, { unique: true })
Enter fullscreen mode Exit fullscreen mode

Text Index

db.posts.createIndex({ content: "text" })
Enter fullscreen mode Exit fullscreen mode

13. Aggregation Framework (Core Feature)

Pipeline Stages

Stage Description
$match filter
$group grouping
$project reshape
$sort sort
$limit limit
$skip skip
$lookup join
$unwind flatten array

Example

db.orders.aggregate([
  { $match: { status: "paid" } },
  {
    $group: {
      _id: "$userId",
      total: { $sum: "$amount" }
    }
  }
])
Enter fullscreen mode Exit fullscreen mode

14. Relationships in MongoDB

Embedded

{
  "name": "User",
  "address": { "city": "Kabul" }
}
Enter fullscreen mode Exit fullscreen mode

Referenced

{
  "userId": ObjectId("...")
}
Enter fullscreen mode Exit fullscreen mode

15. Transactions (ACID)

MongoDB supports multi-document transactions.

const session = db.getMongo().startSession()
session.startTransaction()

try {
  session.getDatabase("shop").orders.insertOne({ total: 100 })
  session.commitTransaction()
} catch (e) {
  session.abortTransaction()
}
Enter fullscreen mode Exit fullscreen mode

16. Security

Authentication

  • SCRAM
  • X.509
  • LDAP

Authorization (RBAC)

db.createUser({
  user: "admin",
  pwd: "password",
  roles: ["readWrite"]
})
Enter fullscreen mode Exit fullscreen mode

17. Backup & Restore

Backup

mongodump --db mydb
Enter fullscreen mode Exit fullscreen mode

Restore

mongorestore mydb
Enter fullscreen mode Exit fullscreen mode

18. MongoDB Compass & Shell

Shell Commands

mongosh
Enter fullscreen mode Exit fullscreen mode

Compass

  • GUI for querying
  • Schema visualization
  • Index management

19. MongoDB Use Cases

  • Web applications
  • Real-time analytics
  • IoT
  • CMS
  • Social networks
  • Microservices

20. MongoDB vs SQL (Quick Comparison)

Feature MongoDB SQL
Schema Flexible Fixed
Joins Limited Strong
Scaling Horizontal Vertical
Transactions Yes Yes

21. Best Practices

  • Use indexes wisely
  • Avoid unbounded arrays
  • Prefer embedding for performance
  • Monitor memory usage
  • Design shard keys carefully

22. Conclusion

MongoDB is a powerful, flexible, and scalable database built for modern applications. Understanding its internals, architecture, and full query syntax allows developers to build high-performance, fault-tolerant systems at scale.

If you master MongoDB deeply, you can confidently design real-world production databases without limitations.

Top comments (0)