MongoDB is one of the most popular NoSQL databases used for building scalable and high-performance applications. It stores data in flexible, JSON-like documents instead of traditional tables. One of the core concepts in MongoDB is CRUD operations, which stands for Create, Read, Update, and Delete.
Understanding MongoDB CRUD operations is essential for developers working with modern web applications, backend systems, and data-driven platforms. These operations allow you to interact with the database efficiently and manage your data lifecycle.
CRUD operations represent the four basic operations performed on any database:
In MongoDB, these operations are performed using collections and documents. A collection is similar to a table in relational databases, while a document is similar to a row.
The Create operation in MongoDB is used to insert new documents into a collection. MongoDB automatically creates a collection if it does not exist when inserting a document.
The insertOne() method is used to insert a single document into a collection.
db.users.insertOne({
name: "John Doe",
age: 28,
email: "john@example.com",
isActive: true
});
This command inserts one document into the "users" collection. If the collection does not exist, MongoDB creates it automatically.
To insert multiple documents at once, MongoDB provides the insertMany() method.
db.users.insertMany([
{ name: "Alice", age: 25, email: "alice@example.com" },
{ name: "Bob", age: 30, email: "bob@example.com" },
{ name: "Charlie", age: 35, email: "charlie@example.com" }
]);
This method improves performance by inserting multiple records in a single operation.
Documents in MongoDB are stored in BSON format, which is a binary representation of JSON. Each document has a unique _id field that acts as a primary key.
The Read operation retrieves data from MongoDB collections. MongoDB provides flexible querying capabilities using the find() and findOne() methods.
db.users.find();
This command retrieves all documents from the "users" collection.
db.users.findOne({ name: "Alice" });
This returns the first document that matches the query condition.
db.users.find({ age: { $gt: 25 } });
This query retrieves all users whose age is greater than 25.
db.users.find(
{ age: { $gt: 25 } },
{ name: 1, email: 1, _id: 0 }
);
Projection allows you to include or exclude specific fields in the result.
db.users.find({
$and: [
{ age: { $gt: 25 } },
{ isActive: true }
]
});
Logical operators such as $and, $or, and $not help in building complex queries.
The Update operation modifies existing documents in a collection. MongoDB provides multiple methods to update documents efficiently.
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
);
This updates the age of the user named Alice.
db.users.updateMany(
{ isActive: true },
{ $set: { status: "active" } }
);
This updates all documents where isActive is true.
db.users.replaceOne(
{ name: "Bob" },
{ name: "Bob", age: 32, email: "bob_new@example.com" }
);
This completely replaces the existing document.
db.users.updateOne(
{ name: "John Doe" },
{ $inc: { age: 1 } }
);
This increases the age by 1.
The Delete operation removes documents from a collection. MongoDB provides flexible options for deleting one or multiple documents.
db.users.deleteOne({ name: "Charlie" });
This deletes the first document that matches the condition.
db.users.deleteMany({ age: { $lt: 25 } });
This deletes all documents where age is less than 25.
db.users.deleteMany({});
This removes all documents from the collection but keeps the collection intact.
Upsert is a combination of update and insert. If a document does not exist, MongoDB inserts it.
db.users.updateOne(
{ name: "David" },
{ $set: { age: 40 } },
{ upsert: true }
);
db.users.bulkWrite([
{
insertOne: {
document: { name: "Eve", age: 22 }
}
},
{
updateOne: {
filter: { name: "Alice" },
update: { $set: { age: 27 } }
}
},
{
deleteOne: {
filter: { name: "Bob" }
}
}
]);
Bulk operations improve performance by combining multiple operations.
MongoDB CRUD operations form the foundation of working with MongoDB databases. By mastering Create, Read, Update, and Delete operations, developers can efficiently manage and manipulate data in modern applications.
With flexible schema design, powerful querying capabilities, and scalability, MongoDB is a preferred choice for developers worldwide. Practicing CRUD operations regularly will help you build robust and efficient applications.
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved