Explain CRUD in MongoDB with an example.

SOLUTION....

CRUD in MongoDB

CRUD stands for Create, Read, Update, and Delete, which are the four basic operations performed on data in a database. In MongoDB, data is stored in collections as documents (JSON-like format), and CRUD operations help manage these documents.

1. Create (Insert data)

Used to add new documents into a collection.
Example:

db.students.insertOne({ name: “Rahul”, age: 20, course: “BCA” })

2. Read (Retrieve data)

Used to fetch documents from a collection.
Example:

db.students.find({ name: “Rahul” })

This retrieves all documents where the name is “Rahul”

3. Update (Modify data)

Used to change existing documents in a collection.
Example:

db.students.updateOne(
{ name: “Rahul” },
{ $set: { age: 21 } }
)

This updates Rahul’s age to 21.

4. Delete (Remove data)

Used to remove documents from a collection.
Example:

db.students.deleteOne({ name: “Rahul” })

This deletes the document where the name is “Rahul”.

Summary

  • Create: insertOne() / insertMany()

  • Read: find()

  • Update: updateOne() / updateMany()

  • Delete: deleteOne() / deleteMany()

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.