Simple CRUD Operations in MongoDB
A Beginner-Friendly Guide with Practical Examples
Introduction
CRUD stands for Create, Read, Update, and Delete. These are the basic operations performed in any database, including MongoDB. In this post, we’ll learn how to perform CRUD operations step by step using the MongoDB Shell (mongosh).
Keywords:
MongoDB, CRUD, NoSQL, Insert, Find, Update, Delete, MongoDB shell, database commands
Step 1: Switch to Your Database
First, open your mongosh
terminal and select your database:
use mydb
Step 2: Create (Insert Data)
Insert One Document:
db.users.insertOne({ name: "Champak", age: 52, city: "Varanasi" })
Insert Multiple Documents:
db.users.insertMany([ { name: "Amit", age: 25, city: "Delhi" }, { name: "Priya", age: 28, city: "Mumbai" } ])
Step 3: Read (Find Data)
Find All Documents:
db.users.find()
Find Specific Document (by Name):
db.users.find({ name: "Champak" })
Pretty Print Results:
db.users.find().pretty()
Step 4: Update Data
Update One Document:
db.users.updateOne( { name: "Champak" }, { $set: { age: 23 } } )
Update Multiple Documents:
db.users.updateMany( { city: "Delhi" }, { $set: { city: "New Delhi" } } )
Step 5: Delete Data
Delete One Document:
db.users.deleteOne({ name: "Amit" })
Delete Multiple Documents:
db.users.deleteMany({ city: "Mumbai" })
Step 6: Dropping a Collection
To delete the entire users
collection:
db.users.drop()
Step 7: Dropping the Entire Database
Warning: This will delete the entire database:
db.dropDatabase()
Step 8: Viewing Databases and Collections
Show All Databases:
show dbs
Show All Collections in Current DB:
show collections
Conclusion
With these simple CRUD operations, you’ve taken your first step in working with MongoDB. You can now create, read, update, and delete data from your NoSQL databases easily.
✅ Want a follow-up post on how to connect MongoDB with Node.js or Python? Let me know in the comments!
0 Comments