Database
MongoDB
Overview
MongoDB is the world's most popular NoSQL document database. It stores data in JSON-like BSON document format and is designed with emphasis on scalability, performance, and flexibility. With dynamic schemas and rich query language, it is optimized for modern application development.
Details
MongoDB was developed by 10gen (now MongoDB Inc.) in 2007. To solve the limitations of traditional relational databases, it adopts a document-oriented approach. It stores data in BSON (Binary JSON) format similar to JSON, and achieves improved developer productivity through schema-less design.
Key features of MongoDB:
- Document-oriented database (BSON format)
- Dynamic schemas
- Horizontal scaling (sharding)
- Replication
- Rich query language
- Indexing capabilities
- Aggregation framework
- GridFS (large file storage)
- Geospatial data support
- ACID properties (multi-document transactions since 4.0)
Advantages and Disadvantages
Advantages
- Flexibility: Schema-less design enables rapid development
- Scalability: Excellent horizontal scaling capabilities
- Performance: Fast read and write operations
- Developer-friendly: Intuitive JSON-like data format
- Rich features: Full-text search, geospatial queries, time-series processing
- Cloud integration: Managed service through MongoDB Atlas
- Community: Active community and ecosystem
Disadvantages
- Memory usage: Can consume large amounts of memory
- JOIN limitations: Limited relational JOIN operations
- Data consistency: Need to consider eventual consistency
- Storage usage: BSON uses more storage than JSON
- Learning curve: Need to learn NoSQL concepts and MongoDB-specific features
Key Links
Code Examples
Installation & Setup
# Ubuntu/Debian
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt update
sudo apt install mongodb-org
# macOS (Homebrew)
brew tap mongodb/brew
brew install mongodb-community
# Docker
docker run --name mongodb -p 27017:27017 -d mongo
# Start MongoDB
sudo systemctl start mongod
sudo systemctl enable mongod
# Connect with MongoShell
mongosh
Basic Operations (CRUD)
// Use database
use myapp
// Create collection and insert document (Create)
db.users.insertOne({
name: "John Doe",
email: "[email protected]",
age: 30,
address: {
city: "New York",
state: "NY"
},
hobbies: ["reading", "movies"],
createdAt: new Date()
})
// Insert multiple documents
db.users.insertMany([
{
name: "Jane Smith",
email: "[email protected]",
age: 25,
address: { city: "Los Angeles", state: "CA" }
},
{
name: "Bob Johnson",
email: "[email protected]",
age: 35,
address: { city: "Chicago", state: "IL" }
}
])
// Read documents (Read)
db.users.find()
db.users.findOne({ name: "John Doe" })
db.users.find({ age: { $gte: 30 } })
db.users.find({ "address.city": "New York" })
// Update documents (Update)
db.users.updateOne(
{ name: "John Doe" },
{ $set: { age: 31, email: "[email protected]" } }
)
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { category: "young" } }
)
// Delete documents (Delete)
db.users.deleteOne({ name: "John Doe" })
db.users.deleteMany({ age: { $gt: 40 } })
Data Modeling
// Embedded documents
db.posts.insertOne({
title: "MongoDB Tutorial",
content: "MongoDB is a document database",
author: {
name: "John Doe",
email: "[email protected]"
},
tags: ["mongodb", "nosql", "database"],
comments: [
{
author: "Jane Smith",
text: "Very helpful tutorial",
date: new Date()
}
],
createdAt: new Date()
})
// References (relationships)
db.users.insertOne({
_id: ObjectId("65a1b2c3d4e5f6789abc1234"),
name: "John Doe",
email: "[email protected]"
})
db.orders.insertOne({
userId: ObjectId("65a1b2c3d4e5f6789abc1234"),
items: [
{ product: "Laptop", price: 800 },
{ product: "Mouse", price: 20 }
],
total: 820,
orderDate: new Date()
})
Indexing & Optimization
// Single field index
db.users.createIndex({ email: 1 })
// Compound index
db.users.createIndex({ age: 1, "address.city": 1 })
// Text index (full-text search)
db.posts.createIndex({ title: "text", content: "text" })
// Geospatial index
db.places.createIndex({ location: "2dsphere" })
// View indexes
db.users.getIndexes()
// Check execution plan
db.users.explain().find({ email: "[email protected]" })
// View statistics
db.users.stats()
Practical Examples
// Aggregation framework
db.users.aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: {
_id: "$address.state",
count: { $sum: 1 },
avgAge: { $avg: "$age" }
}},
{ $sort: { count: -1 } }
])
// Full-text search
db.posts.find({ $text: { $search: "MongoDB NoSQL" } })
// Geospatial query
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-74.0059, 40.7128] },
$maxDistance: 1000
}
}
})
// Time-series data query
db.logs.find({
timestamp: {
$gte: ISODate("2024-01-01T00:00:00Z"),
$lt: ISODate("2024-02-01T00:00:00Z")
}
})
Best Practices
// Transactions (requires replica set)
const session = db.getMongo().startSession()
session.startTransaction()
try {
db.accounts.updateOne(
{ _id: "account1" },
{ $inc: { balance: -100 } },
{ session }
)
db.accounts.updateOne(
{ _id: "account2" },
{ $inc: { balance: 100 } },
{ session }
)
session.commitTransaction()
} catch (error) {
session.abortTransaction()
throw error
} finally {
session.endSession()
}
// Bulk operations
const bulk = db.users.initializeUnorderedBulkOp()
bulk.insert({ name: "User1", email: "[email protected]" })
bulk.find({ name: "User2" }).update({ $set: { active: true } })
bulk.find({ name: "User3" }).remove()
bulk.execute()
// Database configuration
// mongod.conf
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: 127.0.0.1
replication:
replSetName: "rs0"
Node.js Usage Example
const { MongoClient } = require('mongodb')
// Connection
const client = new MongoClient('mongodb://localhost:27017')
async function main() {
try {
await client.connect()
const db = client.db('myapp')
const collection = db.collection('users')
// Insert data
await collection.insertOne({
name: 'John Doe',
email: '[email protected]',
age: 30
})
// Find data
const users = await collection.find({ age: { $gte: 25 } }).toArray()
console.log(users)
} finally {
await client.close()
}
}
main().catch(console.error)