MongoDB Topics Documentation

MONGODB

Work with MongoDB, a NoSQL database, to store, query, and
manage application data in a flexible schema.

MongoDB with Node.js

1. What is MongoDB?

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.

2. Install MongoDB Locally or Use Cloud

You can install MongoDB on your local machine or use MongoDB Atlas (cloud database).

3. Install Mongoose Package

Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It helps define schemas and models.

npm install mongoose
4. Connecting to MongoDB

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));
5. Define a Schema and Model

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

6. Create (Insert Data)

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();
7. Read (Fetch Data)

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" });
8. Update (Modify Data)

Use Model.updateOne() or Model.findByIdAndUpdate() to modify existing documents.

User.updateOne({ name: "Alice" }, { $set: { age: 25 } });
// or
User.findByIdAndUpdate("id_here", { age: 30 });
9. Delete (Remove Data)

Use Model.deleteOne() or Model.findByIdAndDelete() to delete documents.

User.deleteOne({ name: "Alice" });
// or
User.findByIdAndDelete("id_here");
10. MongoDB Compass (Optional GUI)

MongoDB Compass is a visual tool to view, filter, and query your MongoDB database without code.

Download MongoDB Compass

MongoDB Advanced Topics

11. Data Validation in Schema

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 }
});
12. Schema Relationships (Refs)

You can create relationships between collections using ref.

const postSchema = new mongoose.Schema({
  title: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});
13. Populating References

Use .populate() to fetch referenced documents in queries.

Post.find().populate("author").then(data => console.log(data));
14. MongoDB Projection

Select specific fields to return using projection (include or exclude fields).

User.find({}, { name: 1, _id: 0 }); // Only return 'name' field
15. Sorting Documents

Use .sort() to sort results by one or more fields.

User.find().sort({ age: -1 }); // Descending order
16. Limiting and Skipping Results

Use .limit() and .skip() to paginate or control output.

User.find().skip(10).limit(5); // Skip 10, return next 5
17. Aggregation Framework

Performs data processing like grouping, averaging, and transforming data.

User.aggregate([
  { $group: { _id: "$age", total: { $sum: 1 } } }
]);
18. Match and Project in Aggregation

$match filters documents; $project changes output fields.

User.aggregate([
  { $match: { age: { $gt: 20 } } },
  { $project: { name: 1, _id: 0 } }
]);
19. Indexing

Improves query performance. createIndex() defines indexes on fields.

User.createIndex({ email: 1 }); // Ascending index on email
20. Unique Index

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)

21. Upsert Operation

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 }
);
22. Bulk Write Operation

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 } } } }
]);
23. MongoDB Transactions

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();
}
24. Error Handling in Mongoose

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));
25. Using Environment Variables

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);
26. Connecting to MongoDB Atlas

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");
27. Mongo Shell Basics

You can run commands directly in MongoDB Shell.

use mydb
db.users.find()
db.users.insertOne({ name: "Demo" })
28. Drop Collection or Database

Use these carefully! Drops a collection or entire DB.

db.users.drop()
db.dropDatabase()
29. MongoDB Backup (mongodump)

Command-line utility to create backups of your database.

mongodump --db=mydb --out=/backup/mydb
30. MongoDB Restore (mongorestore)

Use this to restore data from a backup created by mongodump.

mongorestore /backup/mydb

MongoDB Advanced Topics (31–40)

31. TTL Index (Time-To-Live)

Automatically deletes documents after a certain time period (great for sessions, logs).

db.sessions.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 })
32. Regular Expression Query

You can use regular expressions to filter data similar to SQL’s LIKE.

User.find({ name: { $regex: "^A" } }); // Names starting with A
33. Text Index and Full-Text Search

Allows text searching within fields. Useful for blogs, search bars.

db.posts.createIndex({ title: "text", body: "text" });
db.posts.find({ $text: { $search: "mongodb tutorial" } });
34. Schema-less Nature of MongoDB

MongoDB allows documents in the same collection to have different structures.

Flexibility is useful but must be managed using Mongoose schemas in Node.js.

35. Embedded Documents

You can nest documents within documents (denormalized structure).

const userSchema = new mongoose.Schema({
  name: String,
  address: { city: String, pincode: Number }
});
36. Array of Embedded Documents

Store multiple objects inside a document using arrays.

const blogSchema = new mongoose.Schema({
  title: String,
  comments: [
    { body: String, date: Date }
  ]
});
37. Array Query Operators

MongoDB provides operators like $elemMatch and $in to query arrays.

db.blogs.find({ tags: { $in: ["mongodb"] } });
db.blogs.find({ comments: { $elemMatch: { author: "John" } } });
38. Distinct Query

Returns an array of unique values for a specified field.

db.users.distinct("country");
39. Rename Field

Rename a field in all matching documents.

db.users.updateMany({}, { $rename: { "fullname": "name" } });
40. Add/Remove Field

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)

41. Field Projection (Include/Exclude Fields)

Use projection to control which fields are returned in a query result.

db.users.find({}, { name: 1, _id: 0 }); // Include name, exclude _id
42. Aggregation Pipeline: $group, $sum, $avg

Performs advanced data processing in stages. $group groups data; $sum and $avg calculate values.

db.orders.aggregate([
  { $group: { _id: "$category", total: { $sum: "$price" } } }
]);
43. Lookup (Join-like Operation)

$lookup performs a left outer join between collections.

db.orders.aggregate([
  { $lookup: {
    from: "customers",
    localField: "custId",
    foreignField: "_id",
    as: "customerDetails"
  } }
]);
44. Geospatial Queries

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
    }
  }
});
45. MapReduce (Data Aggregation Tool)

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" }
);
46. Change Streams

Listen to real-time changes in a collection using watch().

const changeStream = db.collection("users").watch();
changeStream.on("change", (next) => console.log(next));
47. Virtuals in Mongoose

Virtuals are properties not stored in MongoDB but computed on the fly.

userSchema.virtual("fullName").get(function () {
  return this.firstName + " " + this.lastName;
});
48. Lean Queries in Mongoose

.lean() returns plain JavaScript objects instead of Mongoose documents — faster for read-only ops.

User.find().lean().then(data => console.log(data));
49. Timestamps in Schema

Enable automatic createdAt and updatedAt timestamps for documents.

const schema = new mongoose.Schema({...}, { timestamps: true });
50. MongoDB Data Modeling Best Practices

– 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 Reference Links

📘 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