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 [Link] that provides a
schema-based solution to model your application data.
2. Installing MongoDB, [Link], and Mongoose
Use MongoDB locally or via MongoDB Atlas (cloud). Install [Link] and use:
`npm install mongoose`
Connect with:
`[Link]('mongodb://localhost:27017/mydb')`
3. Insert Operations (InsertOne, InsertMany)
- MongoDB: [Link]({name: 'Alice'})
- Mongoose: [Link]({name: 'Alice'})
- Express: [Link]('/user', async (req, res) => { await [Link]([Link]) })
Use insertMany() to add multiple documents.
4. Find Operations
- [Link]({}) - Find all
- [Link]({age: {$gt: 18}}) - With filter
- Mongoose: [Link]({})
- Express: [Link]('/users', async (req, res) => { const users = await [Link]() })
5. Update Operations (updateOne, updateMany)
- [Link]({name:'A'}, {$set:{age: 25}})
- Mongoose: [Link]({name:'A'}, {age:25})
- Express: [Link]('/user/:id', async (req, res) => { await [Link]([Link], [Link]) })
MongoDB Master Guide for Students & Developers
6. Delete Operations
- [Link]({name:'A'})
- Mongoose: [Link]({name:'A'})
- Express: [Link]('/user/:id', async (req, res) => { await [Link]([Link]) })
7. Nested Documents and Arrays
MongoDB allows embedded documents:
{name:'A', contacts:[{phone:'123', messages: ['Hi']}]}
Use $push to insert:
[Link]({name:'A'}, {$push:{contacts: {phone:'456'}}})
8. Complex Queries & Operators
- $in, $regex, $elemMatch
- [Link]({name: {$regex: '^A'}})
- Mongoose supports same filters: [Link]({name:/^A/})
9. Aggregation Framework
Use $match, $group, $project, $lookup
- [Link]([{ $match: { total: { $gt: 100 }}}])
- Mongoose: [Link]([...])
10. Mongoose Features
- Schemas with types and validation
- Virtuals: computed fields
- Middleware (pre/post hooks)
- Populate: join-like feature for references
11. [Link] + MongoDB Integration
- Use routes: POST, GET, PUT, DELETE
- Connect DB and use async handlers
MongoDB Master Guide for Students & Developers
- Example: [Link]('/users', async (req, res) => { const data = await [Link]() })
12. Mongo Shell Commands
- show dbs
- use mydb
- show collections
- [Link]()
- 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.