MongoDB Master Guide for Students & Developers
1. What is MongoDB and Mongoose
MongoDB is a NoSQL database that stores data in JSON-like format. It is document-oriented, flexible, and
scalable.
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js that provides a
schema-based solution to model your application data.
2. Installing MongoDB, Node.js, and Mongoose
Use MongoDB locally or via MongoDB Atlas (cloud). Install Node.js and use:
`npm install mongoose`
Connect with:
`mongoose.connect('mongodb://localhost:27017/mydb')`
3. Insert Operations (InsertOne, InsertMany)
- MongoDB: db.users.insertOne({name: 'Alice'})
- Mongoose: User.create({name: 'Alice'})
- Express: app.post('/user', async (req, res) => { await User.create(req.body) })
Use insertMany() to add multiple documents.
4. Find Operations
- db.users.find({}) - Find all
- db.users.find({age: {$gt: 18}}) - With filter
- Mongoose: User.find({})
- Express: app.get('/users', async (req, res) => { const users = await User.find() })
5. Update Operations (updateOne, updateMany)
- db.users.updateOne({name:'A'}, {$set:{age: 25}})
- Mongoose: User.updateOne({name:'A'}, {age:25})
- Express: app.put('/user/:id', async (req, res) => { await User.findByIdAndUpdate(req.params.id, req.body) })
MongoDB Master Guide for Students & Developers
6. Delete Operations
- db.users.deleteOne({name:'A'})
- Mongoose: User.deleteOne({name:'A'})
- Express: app.delete('/user/:id', async (req, res) => { await User.findByIdAndDelete(req.params.id) })
7. Nested Documents and Arrays
MongoDB allows embedded documents:
{name:'A', contacts:[{phone:'123', messages: ['Hi']}]}
Use $push to insert:
db.users.updateOne({name:'A'}, {$push:{contacts: {phone:'456'}}})
8. Complex Queries & Operators
- $in, $regex, $elemMatch
- db.users.find({name: {$regex: '^A'}})
- Mongoose supports same filters: User.find({name:/^A/})
9. Aggregation Framework
Use $match, $group, $project, $lookup
- db.orders.aggregate([{ $match: { total: { $gt: 100 }}}])
- Mongoose: Order.aggregate([...])
10. Mongoose Features
- Schemas with types and validation
- Virtuals: computed fields
- Middleware (pre/post hooks)
- Populate: join-like feature for references
11. Express.js + MongoDB Integration
- Use routes: POST, GET, PUT, DELETE
- Connect DB and use async handlers
MongoDB Master Guide for Students & Developers
- Example: app.get('/users', async (req, res) => { const data = await User.find() })
12. Mongo Shell Commands
- show dbs
- use mydb
- show collections
- db.collection.find()
- insertOne(), updateOne(), deleteOne() all supported from shell
13. Interview Questions and Answers
Q1: What is MongoDB?
A: NoSQL document database, stores JSON-like docs.
Q2: What is difference between updateOne and updateMany?
A: updateOne updates the first match; updateMany updates all.
Q3: Mongoose vs MongoDB?
A: Mongoose gives structure, validation, and model features.