![]() |
VOOZH | about |
CRUD operations are fundamental database actions in MongoDB that enable users to insert, read, update, and delete documents within collections.
Create (insert) operations are used to add new documents to a collection, creating the collection automatically if it does not already exist.
Example 1: We are creating a student collection in the database using the db.createCollection() method.
Example 2: We are inserting details of a single student in the form of document in the student collection using db.collection.insertOne() method.
Example 3: We are inserting details of the multiple students in the form of documents in the student collection using db.collection.insertMany() method.
Read operations are used to retrieve or query documents from a MongoDB collection.
Examples 1: We are retrieving the details of students from the student collection using db.collection.find() method.
Note: pretty() method is used to decorate the result such that it is easy to read.
Example 2: We are retrieving the details of a single student from the student collection using the db.collection.findOne() method.
Update operations are used to modify existing documents in a MongoDB collection based on specified query conditions.
Example 1: We are updating the age of Alen in the student collection using db.collection.updateOne() method.
Example 2: We are updating the year of course in all the documents in the student collection using db.collection.updateMany() method.
Example 3: We are replacing the complete details of a single student document in the student collection using the db.student.replaceOne() method.
Delete operations are used to remove documents from a MongoDB collection.
Example 1: We are deleting a document from the student collection using db.collection.deleteOne() method.
Example 2: We are deleting multiple documents from the student collection using db.collection.deleteMany() method (all documents are deleted only if an empty filter {} is used).