MongoDB Node.js Integration
MongoDB CRUD Operations Guide
Connect to MongoDB
MongoDB connection create karna aur data operations start karna simple aur scalable hota hai.
import mongoose from "mongoose"
mongoose.connect("mongodb://localhost:27017/myapp")
const db = mongoose.connection
db.once("open", () => console.log("Connected to MongoDB"))
Create Schema and Model
Schema aur model define karna structured data aur validation ke liye essential hai.
const userSchema = new mongoose.Schema({
name: String,
age: Number
})
const User = mongoose.model("User", userSchema)
Insert Documents
Data insert karna easy hai, multiple documents ek sath ya single add kiya ja sakta hai.
await User.create({ name: "Ali", age: 25 })
Query Data
MongoDB se data retrieve karna simple aur flexible queries ke saath possible hai.
const users = await User.find({ age: { $gt: 20 } })
console.log(users)
Update Documents
Existing documents update karna MongoDB me straightforward hai, dynamic aur conditional updates support ke saath.
await User.updateOne({ name: "Ali" }, { $set: { age: 26 } })
Delete Documents
Documents remove karna MongoDB me easy hai, filter aur conditions ke saath.
await User.deleteOne({ name: "Ali" })
Aggregation for Analytics
Aggregation pipelines data analyze aur summarize karne ke liye use hote hain.
const stats = await User.aggregate([{ $group: { _id: "$age", total: { $sum: 1 } } }])
console.log(stats)
Indexing for Performance
Indexes queries fast banate hain, large datasets me performance improve hoti hai.
userSchema.index({ name: 1 })
Validation and Constraints
Validation rules aur constraints data consistency aur integrity maintain karte hain.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, min: 0 }
})
Transactions for Atomic Operations
Transactions multiple operations ko atomic banate hain, data consistency ensure karte hain.
const session = await mongoose.startSession()
session.startTransaction()
await User.create([{ name: "Zubair" }], { session })
await session.commitTransaction()
session.endSession()