In this article, we will learn MongoDB CRUD operations. CRUD means:
- C → Create
- R → Read
- U → Update
- D → Delete
Today we will focus on Create (Insert) and Read (Find).
1. Insert One Document
To insert one document into a collection:
db.students.insertOne({
name: "Rahul",
age: 23,
course: "BCA"
})
Output:
acknowledged: true
MongoDB automatically creates an _id for each document.
2. Insert Multiple Documents
db.students.insertMany([
{ name: "Anu", age: 21, course: "BSc" },
{ name: "Ravi", age: 22, course: "BCom" }
])
Multiple documents inserted at once.
3. Read All Documents
To view all documents:
db.students.find()
4. Read One Document
db.students.findOne({ name: "Rahul" })
This returns only one matching document.
5. Filter Data
Find students with age 22:
db.students.find({ age: 22 })
6. Real-Life Example
Imagine an e-commerce website.
- Insert product → insertOne()
- View products → find()
- Search product → find({name: "Laptop"})
Same logic applies in real applications.
7. Understanding _id Field
Each document has a unique _id field.
{
_id: ObjectId("652ab12345"),
name: "Rahul",
age: 23
}
This helps MongoDB uniquely identify each record.
8. Difference Between find() and findOne()
find()
- Returns multiple documents
- Returns cursor
- Used for listing data
findOne()
- Returns single document
- Stops after first match
- Used for search
9. Common Mistakes
- Wrong collection name
- Forgetting curly brackets { }
- Typing field names incorrectly
Always check spelling carefully.
Conclusion
In this article, you learned:
- insertOne()
- insertMany()
- find()
- findOne()
- Filtering documents
You can now create and read data in MongoDB confidently.
In the next article, we will learn MongoDB Query Operators ($gt, $lt, $eq, $ne).
Your MongoDB Zero to Hero journey is becoming powerful 🚀