MongoDB CRUD Operations – Simplified

Introduction

MongoDB is a popular document-oriented database that offers high performance, scalability, and flexibility. One of the most important features of MongoDB is the ability to perform CRUD operations. CRUD stands for Create, Read, Update, and Delete, and it’s a set of basic operations that any database system should support.

In this post, we’ll explore the basics of MongoDB CRUD operations and how they can be used to manipulate data in a MongoDB database.

Create Operation

The Create operation is used to insert new data into a MongoDB database. In MongoDB, data is organized into collections, which are analogous to tables in a relational database. To create a new document in a collection, you can use the insertOne() or insertMany() methods.

Here’s an example of how to insert a new document into a collection called “users”:

db.users.insertOne({ name: "John Doe", age: 35, email: "johndoe@example.com" })

The insertOne() method inserts a single document into the “users” collection with the specified fields.

Read Operation

The Read operation is used to retrieve data from a MongoDB database. To read data from a collection, you can use the find() method.

Here’s an example of how to retrieve all documents from the “users” collection:

db.users.find()

This will return all the documents in the “users” collection.

You can also specify query criteria to retrieve only specific documents. For example, to retrieve all documents where the age is greater than or equal to 30, you can use the following query:

db.users.find({ age: { $gte: 30 } })

Update Operation

The Update operation is used to modify existing data in a MongoDB database. To update a document in a collection, you can use the updateOne() or updateMany() methods.

Here’s an example of how to update the email address of a user with the name “John Doe”:

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

The updateOne() method updates the first document that matches the query criteria. The $set operator sets the value of the email field to “newemail@example.com“.

Delete Operation

The Delete operation is used to remove data from a MongoDB database. To delete a document from a collection, you can use the deleteOne() or deleteMany() methods.

Here’s an example of how to delete a document from the “users” collection where the name is “John Doe”:

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

The deleteOne() method removes the first document that matches the query criteria.

Conclusion

In this post, we’ve covered the basics of MongoDB CRUD operations. We’ve explored how to create, read, update, and delete data in a MongoDB database. By mastering these operations, you’ll be able to manipulate data in your MongoDB database with ease.

  • Ask Question