MONGODB
Work with MongoDB, a NoSQL database, to store, query, and
manage application data in a flexible schema.
MongoDB with Node.js
MongoDB is a NoSQL, document-oriented database that stores data in flexible, JSON-like documents called BSON.
Unlike relational databases, MongoDB doesn’t use tables — it uses collections and documents.
You can install MongoDB on your local machine or use MongoDB Atlas (cloud database).
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It helps define schemas and models.
npm install mongoose
Use the mongoose.connect() method to establish a
connection with the database.
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mydb")
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.error(err));
A Schema defines the structure of a document, and a Model is used to create and manage documents.
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model("User", userSchema);
CRUD Operations in MongoDB
Use new Model().save() or Model.create() to
insert documents into a collection.
const newUser = new User({ name: "Alice", email:
"alice@example.com", age: 22 });
newUser.save();
Use Model.find() to retrieve documents. You can filter,
limit, or sort the results.
User.find().then(data => console.log(data));
User.findOne({ name: "Alice" });
Use Model.updateOne() or
Model.findByIdAndUpdate() to modify existing documents.
User.updateOne({ name: "Alice" }, { $set: { age: 25 } });
// or
User.findByIdAndUpdate("id_here", { age: 30 });
Use Model.deleteOne() or
Model.findByIdAndDelete() to delete documents.
User.deleteOne({ name: "Alice" });
// or
User.findByIdAndDelete("id_here");
MongoDB Compass is a visual tool to view, filter, and query your MongoDB database without code.
MongoDB Advanced Topics
You can enforce structure and rules in MongoDB using Mongoose schema types and validations.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, unique: true },
age: { type: Number, min: 18 }
});
You can create relationships between collections using
ref.
const postSchema = new mongoose.Schema({
title: String,
author: { type: mongoose.Schema.Types.ObjectId, ref:
'User' }
});
Use .populate() to fetch referenced documents in queries.
Post.find().populate("author").then(data => console.log(data));
Select specific fields to return using projection (include or exclude fields).
User.find({}, { name: 1, _id: 0 }); // Only return 'name' field
Use .sort() to sort results by one or more fields.
User.find().sort({ age: -1 }); // Descending order
Use .limit() and .skip() to paginate or
control output.
User.find().skip(10).limit(5); // Skip 10, return next 5
Performs data processing like grouping, averaging, and transforming data.
User.aggregate([
{ $group: { _id: "$age", total: { $sum: 1 } } }
]);
$match filters documents; $project changes
output fields.
User.aggregate([
{ $match: { age: { $gt: 20 } } },
{ $project: { name: 1, _id: 0 } }
]);
Improves query performance. createIndex() defines indexes
on fields.
User.createIndex({ email: 1 }); // Ascending index on email
Prevents duplicate entries in a collection field (e.g., email, username).
const schema = new mongoose.Schema({
email: { type: String, unique: true }
});
MongoDB Advanced Topics (21–30)
Upsert is a combination of update + insert. If no document matches, it inserts a new one.
User.updateOne(
{ email: "john@example.com" },
{ $set: { name: "John" } },
{ upsert: true }
);
Allows you to run multiple write operations (insert, update, delete) in a single call.
User.bulkWrite([
{ insertOne: { document: { name: "Tom" } } },
{ updateOne: { filter: { name: "Tom" }, update: { $set:
{ age: 30 } } } }
]);
Used to execute multiple operations as a single atomic unit (mostly with replica sets).
const session = await mongoose.startSession();
session.startTransaction();
try {
// perform operations
await session.commitTransaction();
} catch (err) {
await session.abortTransaction();
}
Always catch and handle errors using try-catch or
.catch().
User.findById("wrongID")
.then(data => console.log(data))
.catch(err => console.error("Error:", err.message));
Store your MongoDB URI in a secure file (.env) instead of hardcoding.
// .env
MONGO_URI=mongodb://localhost:27017/mydb
// index.js
require("dotenv").config();
mongoose.connect(process.env.MONGO_URI);
MongoDB Atlas is a cloud version of MongoDB. Use your cluster URI to connect.
mongoose.connect("mongodb+srv://username:password@cluster.mongodb.net/mydb?retryWrites=true");
You can run commands directly in MongoDB Shell.
use mydb
db.users.find()
db.users.insertOne({ name: "Demo" })
Use these carefully! Drops a collection or entire DB.
db.users.drop()
db.dropDatabase()
Command-line utility to create backups of your database.
mongodump --db=mydb --out=/backup/mydb
Use this to restore data from a backup created by
mongodump.
mongorestore /backup/mydb
MongoDB Advanced Topics (31–40)
Automatically deletes documents after a certain time period (great for sessions, logs).
db.sessions.createIndex({ "createdAt": 1 }, { expireAfterSeconds:
3600 })
You can use regular expressions to filter data similar to SQL’s LIKE.
User.find({ name: { $regex: "^A" } }); // Names starting with A
Allows text searching within fields. Useful for blogs, search bars.
db.posts.createIndex({ title: "text", body: "text" });
db.posts.find({ $text: { $search: "mongodb tutorial" } });
MongoDB allows documents in the same collection to have different structures.
Flexibility is useful but must be managed using Mongoose schemas in Node.js.
You can nest documents within documents (denormalized structure).
const userSchema = new mongoose.Schema({
name: String,
address: { city: String, pincode: Number }
});
Store multiple objects inside a document using arrays.
const blogSchema = new mongoose.Schema({
title: String,
comments: [
{ body: String, date: Date }
]
});
MongoDB provides operators like $elemMatch and
$in to query arrays.
db.blogs.find({ tags: { $in: ["mongodb"] } });
db.blogs.find({ comments: { $elemMatch: { author: "John" } } });
Returns an array of unique values for a specified field.
db.users.distinct("country");
Rename a field in all matching documents.
db.users.updateMany({}, { $rename: { "fullname": "name" } });
You can add or remove fields using $set and
$unset.
db.users.updateMany({}, { $set: { isActive: true } });
db.users.updateMany({}, { $unset: { age: "" } });
MongoDB Topics (41–50)
Use projection to control which fields are returned in a query result.
db.users.find({}, { name: 1, _id: 0 }); // Include name, exclude _id
Performs advanced data processing in stages. $group groups data; $sum and $avg calculate values.
db.orders.aggregate([
{ $group: { _id: "$category", total: { $sum: "$price" }
} }
]);
$lookup performs a left outer join between collections.
db.orders.aggregate([
{ $lookup: {
from: "customers",
localField: "custId",
foreignField: "_id",
as: "customerDetails"
} }
]);
Used to store and query location-based data (longitude & latitude).
db.places.createIndex({ location: "2dsphere" });
db.places.find({
location: {
$near: {
$geometry: { type: "Point",
coordinates: [77.5946, 12.9716] },
$maxDistance: 5000
}
}
});
MapReduce allows you to apply custom map and reduce functions on large datasets.
db.orders.mapReduce(
function() { emit(this.product, this.quantity); },
function(key, values) { return Array.sum(values); },
{ out: "product_totals" }
);
Listen to real-time changes in a collection using
watch().
const changeStream = db.collection("users").watch();
changeStream.on("change", (next) => console.log(next));
Virtuals are properties not stored in MongoDB but computed on the fly.
userSchema.virtual("fullName").get(function () {
return this.firstName + " " + this.lastName;
});
.lean() returns plain JavaScript objects instead of
Mongoose documents — faster for read-only ops.
User.find().lean().then(data => console.log(data));
Enable automatic createdAt and
updatedAt timestamps for documents.
const schema = new mongoose.Schema({...}, { timestamps: true });
– Use embedding for one-to-few relationships
– Use references for one-to-many or many-to-many
– Avoid large documents (max: 16MB)
– Use schema validation for consistency
– Index fields used in queries
📘 MongoDB Official Docs: https://www.mongodb.com/docs/
📦 Mongoose Docs: https://mongoosejs.com/docs/
🌐 MongoDB Atlas Cloud: https://www.mongodb.com/cloud/atlas
🎓 GeeksforGeeks MongoDB Tutorial: https://www.geeksforgeeks.org/mongodb/
🛠️ MongoDB Compass Tool: https://www.mongodb.com/products/compass