| name | mongodb |
| description | Work with MongoDB databases using best practices. Use when designing schemas, writing queries, building aggregation pipelines, or optimizing performance. Triggers on MongoDB, Mongoose, NoSQL, aggregation pipeline, document database, MongoDB Atlas. |
MongoDB & Mongoose
Build and query MongoDB databases with best practices.
Quick Start
npm install mongodb mongoose
Native Driver
import { MongoClient, ObjectId } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI!);
const db = client.db('myapp');
const users = db.collection('users');
await client.connect();
await users.insertOne({ name: 'Alice', email: 'alice@example.com' });
const user = await users.findOne({ email: 'alice@example.com' });
await users.updateOne({ _id: user._id }, { $set: { name: 'Alice Smith' } });
await users.deleteOne({ _id: user._id });
Mongoose Setup
import mongoose from 'mongoose';
await mongoose.connect(process.env.MONGODB_URI!, {
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
});
mongoose.connection.on('connected', () => console.log('MongoDB connected'));
mongoose.connection.on('error', (err) => console.error('MongoDB error:', err));
mongoose.connection.on('disconnected', () => console.log('MongoDB disconnected'));
process.on('SIGINT', async () => {
await mongoose.connection.close();
process.exit(0);
});
Schema Design
Basic Schema
import mongoose, { Schema, Document, Model } from 'mongoose';
interface IUser extends Document {
email: string;
name: string;
password: string;
role: 'user' | 'admin';
profile: {
avatar?: string;
bio?: string;
};
createdAt: Date;
updatedAt: Date;
}
const userSchema = new Schema<IUser>({
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, 'Invalid email format'],
},
name: {
type: String,
required: true,
trim: true,
minlength: 2,
maxlength: 100,
},
password: {
type: String,
required: true,
select: false,
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user',
},
profile: {
avatar: String,
bio: { type: String, maxlength: 500 },
},
}, {
timestamps: true,
toJSON: {
transform(doc, ret) {
delete ret.password;
delete ret.__v;
return ret;
},
},
});
userSchema.index({ email: 1 });
userSchema.index({ createdAt: -1 });
userSchema.index({ name: 'text', 'profile.bio': 'text' });
const User: Model<IUser> = mongoose.model('User', userSchema);
Embedded Documents vs References
const orderSchema = new Schema({
customer: {
name: String,
email: String,
address: {
street: String,
city: String,
country: String,
},
},
items: [{
product: String,
quantity: Number,
price: Number,
}],
total: Number,
});
const postSchema = new Schema({
title: String,
content: String,
author: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
comments: [{
type: Schema.Types.ObjectId,
ref: 'Comment',
}],
});
const post = await Post.findById(id)
.populate('author', 'name email')
.populate({
path: 'comments',
populate: { path: 'author', select: 'name' },
});
Virtuals
const userSchema = new Schema({
firstName: String,
lastName: String,
});
userSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
userSchema.virtual('posts', {
ref: 'Post',
localField: '_id',
foreignField: 'author',
});
userSchema.set('toJSON', { virtuals: true });
userSchema.set('toObject', { virtuals: true });
Query Operations
Find Operations
const users = await User.find({
role: 'user',
createdAt: { $gte: new Date('2024-01-01') },
});
const results = await User.find()
.where('role').equals('user')
.where('createdAt').gte(new Date('2024-01-01'))
.select('name email')
.sort({ createdAt: -1 })
.limit(10)
.skip(20)
.lean();
const user = await User.findOne({ email: 'alice@example.com' });
const userById = await User.findById(id);
const exists = await User.exists({ email: 'alice@example.com' });
const count = await User.countDocuments({ role: 'admin' });
Query Operators
await User.find({ age: { $eq: 25 } });
await User.find({ age: { $ne: 25 } });
await User.find({ age: { $gt: 25 } });
await User.find({ age: { $gte: 25 } });
await User.find({ age: { $lt: 25 } });
await User.find({ age: { $lte: 25 } });
await User.find({ age: { $in: [20, 25, 30] } });
await User.find({ age: { $nin: [20, 25] } });
await User.find({
$and: [{ age: { $gte: 18 } }, { role: 'user' }],
});
await User.find({
$or: [{ role: 'admin' }, { isVerified: true }],
});
await User.find({ age: { $not: { $lt: 18 } } });
await User.find({ avatar: { $exists: true } });
await User.find({ score: { $type: 'number' } });
await User.find({ tags: 'nodejs' });
await User.find({ tags: { $all: ['nodejs', 'mongodb'] } });
await User.find({ tags: { $size: 3 } });
await User.find({ 'items.0.price': { $gt: 100 } });
await User.find({ $text: { $search: 'mongodb developer' } });
await User.find({ name: { $regex: /^john/i } });
Update Operations
await User.updateOne(
{ _id: userId },
{ $set: { name: 'New Name' } }
);
await User.updateMany(
{ role: 'user' },
{ $set: { isVerified: true } }
);
const updated = await User.findByIdAndUpdate(
userId,
{ $set: { name: 'New Name' } },
{ new: true, runValidators: true }
);
await User.updateOne({ _id: userId }, {
$set: { name: 'New Name' },
$unset: { tempField: '' },
$inc: { loginCount: 1 },
$mul: { score: 1.5 },
$min: { lowScore: 50 },
$max: { highScore: 100 },
$push: { tags: 'new-tag' },
$pull: { tags: 'old-tag' },
$addToSet: { tags: 'unique-tag' },
});
await User.updateOne(
{ email: 'new@example.com' },
{ $set: { name: 'New User' } },
{ upsert: true }
);
Aggregation Pipeline
Basic Aggregation
const results = await Order.aggregate([
{ $match: { status: 'completed' } },
{ $group: {
_id: '$customerId',
totalOrders: { $sum: 1 },
totalSpent: { $sum: '$total' },
avgOrder: { $avg: '$total' },
}},
{ $sort: { totalSpent: -1 } },
{ $limit: 10 },
]);
Pipeline Stages
const pipeline = [
{ $match: { createdAt: { $gte: new Date('2024-01-01') } } },
{ $project: {
name: 1,
email: 1,
yearJoined: { $year: '$createdAt' },
fullName: { $concat: ['$firstName', ' ', '$lastName'] },
}},
{ $lookup: {
from: 'orders',
localField: '_id',
foreignField: 'userId',
as: 'orders',
}},
{ $unwind: { path: '$orders', preserveNullAndEmptyArrays: true } },
{ $group: {
_id: '$_id',
name: { $first: '$name' },
orderCount: { $sum: 1 },
orders: { $push: '$orders' },
}},
{ $addFields: {
hasOrders: { $gt: ['$orderCount', 0] },
}},
{ $facet: {
topCustomers: [{ $sort: { orderCount: -1 } }, { $limit: 5 }],
stats: [{ $group: { _id: null, avgOrders: { $avg: '$orderCount' } } }],
}},
];
Analytics Examples
const salesByMonth = await Order.aggregate([
{ $match: { status: 'completed' } },
{ $group: {
_id: {
year: { $year: '$createdAt' },
month: { $month: '$createdAt' },
},
totalSales: { $sum: '$total' },
orderCount: { $sum: 1 },
}},
{ $sort: { '_id.year': -1, '_id.month': -1 } },
]);
const topProducts = await Order.aggregate([
{ $unwind: '$items' },
{ $group: {
_id: '$items.productId',
totalQuantity: { $sum: '$items.quantity' },
totalRevenue: { $sum: { $multiply: ['$items.price', '$items.quantity'] } },
}},
{ $lookup: {
from: 'products',
localField: '_id',
foreignField: '_id',
as: 'product',
}},
{ $unwind: '$product' },
{ $project: {
name: '$product.name',
totalQuantity: 1,
totalRevenue: 1,
}},
{ $sort: { totalRevenue: -1 } },
{ $limit: 10 },
]);
Middleware (Hooks)
userSchema.pre('save', async function(next) {
if (this.isModified('password')) {
this.password = await bcrypt.hash(this.password, 12);
}
next();
});
userSchema.post('save', function(doc) {
console.log('User saved:', doc._id);
});
userSchema.pre(/^find/, function(next) {
this.find({ isDeleted: { $ne: true } });
next();
});
userSchema.pre('aggregate', function(next) {
this.pipeline().unshift({ $match: { isDeleted: { $ne: true } } });
next();
});
Transactions
const session = await mongoose.startSession();
try {
session.startTransaction();
const user = await User.create([{ name: 'Alice' }], { session });
await Account.create([{ userId: user[0]._id, balance: 0 }], { session });
await Order.updateOne({ _id: orderId }, { $set: { status: 'paid' } }, { session });
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}
await mongoose.connection.transaction(async (session) => {
await User.create([{ name: 'Alice' }], { session });
await Account.create([{ userId: user._id }], { session });
});
Indexing
userSchema.index({ email: 1 });
userSchema.index({ role: 1, createdAt: -1 });
userSchema.index({ email: 1 }, { unique: true });
userSchema.index(
{ email: 1 },
{ partialFilterExpression: { isActive: true } }
);
sessionSchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 });
postSchema.index({ title: 'text', content: 'text' });
locationSchema.index({ coordinates: '2dsphere' });
const indexes = await User.collection.getIndexes();
Performance Tips
const users = await User.find().lean();
const users = await User.find().select('name email');
const cursor = User.find().cursor();
for await (const user of cursor) {
}
const bulkOps = [
{ insertOne: { document: { name: 'User 1' } } },
{ updateOne: { filter: { _id: id1 }, update: { $set: { name: 'Updated' } } } },
{ deleteOne: { filter: { _id: id2 } } },
];
await User.bulkWrite(bulkOps);
const explanation = await User.find({ role: 'admin' }).explain('executionStats');
MongoDB Atlas
const uri = 'mongodb+srv://user:password@cluster.mongodb.net/dbname?retryWrites=true&w=majority';
const results = await Product.aggregate([
{ $search: {
index: 'default',
text: {
query: 'wireless headphones',
path: ['name', 'description'],
fuzzy: { maxEdits: 1 },
},
}},
{ $project: {
name: 1,
score: { $meta: 'searchScore' },
}},
]);
const results = await Product.aggregate([
{ $vectorSearch: {
index: 'vector_index',
path: 'embedding',
queryVector: [0.1, 0.2, ...],
numCandidates: 100,
limit: 10,
}},
]);
Resources