CRUD operations on MongoDB
In this article, I am going to explain how to Create, Read, Update and Delete in MongoDB.
Create Operation
The create or insert operations are used to insert or add new documents in the collection. If a collection does not exist, then it will create a new collection in the database.
MongoDB provides the following methods to insert documents into a collection:
- db.collection.insertOne(): It is used to insert a single document in the collection.
Example
db.collection.insert_one({
"name" : "John",
"branch" : "CSE"
"year" : "2019"
})
- db.collection.insertMany(): It is used to insert multiple documents in the collection.
Example
db.collection.insert_one({
"name" : "Sekar",
"branch" : "ECE"
"year" : "2020"
}, {
"name" : "Steve",
"branch" : "IT"
"year" : "2018"
})
Read Operation
The Read operations are used to retrieve documents from the collection, or in other words, read operations are used to query a collection for a document.
MongoDB provides the following methods to read documents from a collection:
- db.collection.find(): It is used to retrieve documents from the collection.
Example
db.collection.find({name:"John"})
Update Operation
The update operations are used to update or modify the existing document in the collection.
MongoDB provides the following methods to update documents of a collection:
- db.collection.updateOne(): It is used to update a single document in the collection that satisfy the given criteria.
Example
db.collection.updateOne({name : "John"},{$set:{branch:"EEE"}})
- db.collection.updateMany(): It is used to update multiple documents in the collection that satisfy the given criteria.
Example
db.collection.updateMany({},{$set:{year:2021}})
- db.collection.replaceOne(): It is used to replace a single document in the collection that satisfies the given criteria.
Example
db.collection.replace_one(
{
"name" : "Sekar"},
{
"name" : "Suresh",
"branch": "Mechanical",
"year" : 2020
})
Delete Operation
The delete operation is used to delete or remove the documents from a collection.
MongoDB provides the following methods to delete documents of a collection:
- db.collection.deleteOne(): It is used to delete a single document from the collection that satisfies the given criteria.
Example
db.collection.deleteOne({name : "Steve"})
- db.collection.deleteMany(): It is used to delete multiple documents from the collection that satisfy the given criteria.
Example
The below example deletes all the documents from the collection.
db.collection.deleteMany({})
Thanks for Reading!!