MongoDB is a NoSQL database that stores data as JSON-like documents instead of rows in tables. Instead of defining a rigid schema upfront, you store flexible documents that can have different fields β making it easy to iterate quickly on your data model.
Itβs one of the most popular databases in the world, especially for JavaScript/Node.js projects where the document model maps naturally to JavaScript objects.
Documents vs tables
In a relational database (PostgreSQL, MySQL), data lives in tables with fixed columns:
-- Relational: every user has the same columns
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
age INTEGER
);
In MongoDB, data lives in collections of documents:
// MongoDB: each document can have different fields
{
_id: ObjectId("..."),
name: "Alice",
email: "alice@example.com",
age: 30,
skills: ["JavaScript", "Python"], // arrays are native
address: { // nested objects are native
city: "Brussels",
country: "Belgium"
}
}
No migrations needed. You can add fields to new documents without changing existing ones.
Basic operations
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('myapp');
// Insert
await db.collection('users').insertOne({
name: 'Alice',
email: 'alice@example.com',
skills: ['JavaScript', 'Python'],
});
// Find
const user = await db.collection('users').findOne({ email: 'alice@example.com' });
// Update
await db.collection('users').updateOne(
{ email: 'alice@example.com' },
{ $set: { age: 31 }, $push: { skills: 'Go' } }
);
// Delete
await db.collection('users').deleteOne({ email: 'alice@example.com' });
// Query with filters
const devs = await db.collection('users')
.find({ skills: 'JavaScript', age: { $gte: 25 } })
.sort({ name: 1 })
.limit(10)
.toArray();
When to use MongoDB
Good fit:
- Rapid prototyping β no schema migrations, just store what you need
- Content management β blog posts, products, user profiles with varying fields
- Real-time analytics β high write throughput for event logging
- IoT and time-series data β flexible schemas for sensor data
- JavaScript/Node.js stacks β documents map directly to JS objects
Not ideal:
- Complex relationships β if you need lots of JOINs, a relational database is better
- Transactions across collections β MongoDB supports transactions but theyβre not as mature as PostgreSQLβs
- Strict data integrity β if you need enforced schemas and foreign keys, use PostgreSQL
- Reporting and analytics β SQL is more powerful for complex queries
MongoDB vs PostgreSQL
| MongoDB | PostgreSQL | |
|---|---|---|
| Data model | Documents (JSON) | Tables (rows/columns) |
| Schema | Flexible | Strict (with migrations) |
| Query language | MongoDB Query Language | SQL |
| Joins | Limited ($lookup) | Full JOIN support |
| Transactions | Supported (since 4.0) | Mature, battle-tested |
| Best for | Flexible data, rapid dev | Complex relationships, integrity |
For a deeper comparison, see MongoDB vs PostgreSQL.
Mongoose (ODM for Node.js)
Most Node.js projects use Mongoose, an ODM (Object Document Mapper) that adds schema validation and convenience methods:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
skills: [String],
createdAt: { type: Date, default: Date.now },
});
const User = mongoose.model('User', userSchema);
const alice = await User.create({ name: 'Alice', email: 'alice@example.com' });
FAQ
When should I choose MongoDB over PostgreSQL?
Choose MongoDB when your data is naturally document-shaped (nested objects, arrays, varying fields), you need rapid iteration without migrations, or youβre building content-heavy apps like CMSes and product catalogs. If your data has lots of relationships and you need complex joins, PostgreSQL is the better choice.
Is MongoDB good for large-scale production apps?
Yes, MongoDB powers production workloads at companies handling millions of requests per second. It supports horizontal scaling through sharding, replica sets for high availability, and has mature tooling for monitoring and backups. The key is proper index design and understanding its consistency model.
Do I need Mongoose to use MongoDB with Node.js?
No, the official MongoDB Node.js driver works perfectly fine without Mongoose. Mongoose adds schema validation, middleware hooks, and convenience methods that many teams find helpful, but itβs an extra layer of abstraction. For simpler projects or when you want more control, the native driver is lighter and faster.
Learn more
- MongoDB cheat sheet β quick reference for queries
- What is an ORM? β how ORMs and ODMs work
- What is a REST API? β building APIs on top of MongoDB
- Docker complete guide β running MongoDB in containers
Related: What is Redis