MongoDB Tutorial
- Home
- Introduction
- Installation
- Connection & Databases
- CRUD Operations
- Comparison Operators
- Logical Operators
- Array Operators
- Evaluation Operators
- Update Operators
- Projection & Sorting
- Cursor Methods
- Querying Nested Docs
- Upserts & Indexes
- Aggregation Framework
- Data Modeling
- Validations & Transactions
- Geospatial Queries
- Advanced Indexing
- MongoDB with Next.js
- Best Practices
CRUD Operations
CRUD stands for Create, Read, Update, and Delete. These are the four basic functions of persistent storage.
1. CREATE (Insert)
Use `insertOne()` for a single document and `insertMany()` for multiple.
// Insert One
db.users.insertOne({
name: "John Doe",
age: 30,
email: "john@example.com"
})
// Insert Many
db.users.insertMany([
{ name: "Jane", age: 25 },
{ name: "Bob", age: 35 }
])2. READ (Find)
Use `find()` to query documents. You can pass a filter object to refine results.
// Find All
db.users.find()
// Find with Filter
db.users.find({ name: "John Doe" })
// Find One (Returns the first matching document)
db.users.findOne({ age: { $gt: 25 } })3. UPDATE
Use `updateOne()`, `updateMany()`, or `replaceOne()`. Always use the `$set` operator to update specific fields.
// Update One
db.users.updateOne(
{ name: "John Doe" }, // filter
{ $set: { age: 31 } } // update
)
// Update Many
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "active" } }
)4. DELETE
Use `deleteOne()` or `deleteMany()` to remove documents from a collection.
// Delete One
db.users.deleteOne({ name: "John Doe" })
// Delete Many
db.users.deleteMany({ status: "inactive" })
// Delete All Documents (Use with caution!)
db.users.deleteMany({})Pro Tip: All write operations (Create, Update, Delete) are atomic at the document level.