How To Perform CRUD Operations in MongoDB

Share your love

MongoDB is a popular NoSQL database that stores data in the form of BSON (Binary JSON) documents. It is an open-source, document-oriented database management system designed for scalability, performance, and high availability.

CRUD stands for Create, Read, Update, and Delete.

  • Create operations involve adding new data to the database.
  • Read operations retrieve data from the database by running queries.
  • Update operations modify existing data in the database.
  • Delete operations remove data from the database permanently.

These are the basic operations that can be performed on any database. Here’s how you can perform CRUD operations on MongoDB:

Creating documents

To create a new document in MongoDB, you can use the insertOne() method. For example, to create a new user document with a name and an email, you can use the following code:

db.users.insertOne({
  name: "John Doe",
  email: "john.doe@example.com"
});

Reading documents

To retrieve data from MongoDB, you can use the find() method. For example, to retrieve all the users in the users collection, you can use the following code:

db.users.find();

You can also filter the data using various parameters, like this:

db.users.find({ name: "John Doe" });

Updating documents

To update a document in MongoDB, you can use the updateOne() or updateMany() method. For example, to update the email address of a user document with the name “John Doe”, you can use the following code:

db.users.updateOne(
  { name: "John Doe" },
  { $set: { email: "john.doe.new@example.com" } }
);

Deleting documents

To delete a document in MongoDB, you can use the deleteOne() or deleteMany() method. For example, to delete a user document with the name “John Doe”, you can use the following code:

db.users.deleteOne({ name: "John Doe" });

In conclusion, performing CRUD operations on MongoDB is a fundamental aspect of working with the database. MongoDB provides a user-friendly interface to execute these operations using various methods and operators. With the help of these operations, one can effectively manage the data in the database and perform all the essential tasks such as creating, reading, updating, and deleting the data. As with any database management system, it is crucial to ensure data integrity and security while performing these operations. With proper care and attention to detail, MongoDB can be an excellent choice for storing and managing data.

Share your love