CRUD operations in MongoDB mean “create, read, update, and delete documents.”
MongoDB stores data in BSON – Binary encoded JSON documents that support a substantial, rich collection of types.
Namely, Fields in BSON documents may hold arrays of values or embedded documents as a requirement. Therefore, the record in MongoDB is a document described below and a data structure formed of field and value pairs.
Step 1: Start Mongo Server and Mongo Shell
Now, first, start the Mongo server using the following command.
mongod
Also, start the Mongo shell using the following command.
mongo
Step 2: Create a database and collection.
Switch to an existing database or create a new Mongodb database using the following command.
use crud
We switched to that database.
Now, create a collection using the following command. Finally, let us call the collection operate.
db.createCollection("operate")
The collection is created. Then, MongoDB stores the documents in the collections. Collections are somewhat the same as tables in relational databases. If the collection does not exist, then MongoDB creates the collection for you when you first store data for that collection.
Step 3: Create Operations in MongoDB
Create or insert operations and add new documents to a collection. If the collection does not currently exist, insert operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:
- db.collection.insertOne()
- db.collection.insertMany()
In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.
MongoDB provides the following methods to insert the documents into a collection.
Create or insert operations and add new documents to the collection. If the collection does not exist, then insert operations will create the collection.
The command db.collection.insert() will perform the insert operation into the collection of the document.
Insert Multiple Documents in MongoDB
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
It returns the following document containing:
- A boolean was acknowledged as valid if the operation ran with write concern or false if write concern was disabled.
- An array of _id for each successfully inserted document.
We can insertMany() documents like the following code.
db.operate.insertMany([{ enrollno: "110470116021", name: "Krunal Lathiya", college: "VVP Engineering College", course: { courseName: "BE IT", duration: "4 Years" }, address: { city: "Rajkot", state: "Gujarat", country: "India" } },{ enrollno: "110470116022", name: "Rushikesh Vekariya", college: "VVP Engineering College", course: { courseName: "BE IT", duration: "4 Years" }, address: { city: "Rajkot", state: "Gujarat", country: "India" } }])
Step 4: MongoDB Read Operations
Read operations retrieves the documents from the collection, i.e., queries the collection for the documents. MongoDB provides us with the following methods to read the documents from the collection.
db.collection.find()
Let us retrieve all the documents using the following query.
You can specify the query filters or criteria identifying the documents to return.
db.operate.find().limit(2)
Also, we can get pretty results.
db
.operate
.find()
.limit(2)
.pretty()
Step 5: MongoDB Update Operations
Update operations and modify existing documents in the collection. MongoDB provides us with the following methods to update the collection documents.
- db.collection.updateOne()
- db.collection.updateMany()
- db.collection.replaceOne()
You can write the update query in MongoDB like the one below.
db.operate.updateOne(
{ name: "Rushikesh Vekariya" },
{
$set: {college: "Marwadi"}
}
)
In MongoDB, the update operations target a single collection. All the write operations in MongoDB are atomic on the level of the single document.
db.operate.updateMany(
{ name: "Krunal Lathiya" },
{
$set: {city: "Jetpur"}
}
)
In the operate collection, we have two documents named Krunal Lathiya, so it will update both documents using updateMany.
The db.collection.replaceOne() replaces a single document within the collection based on the filter.
The replaceOne() method has the following syntax.
db.collection.replaceOne(
<filter>,
<replacement>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>
}
)
Step 6: MongoDB Delete Operations
The delete operations remove the documents from the collection. MongoDB provides the following methods to delete the documents of the collection.
- db.collection.deleteOne()
- db.collection.deleteMany()
db.operate.deleteOne(
{ name : "Krunal Lathiya" }
)
So, it will remove the document which has the name Krunal Lathiya.
Same syntax, but the deleteMany function deletes all the documents with the provided name.
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Hi Krunal,
I have the following issue. Can you please help me sort it out.
My collection structure is as follows.
{
name: ‘some name’,
values: [
{
val1: ‘some value’,
val2: ‘some value’
},
……….
……….
]
If I am to use updatemany to update all the documents whose ‘ values.val1’ is ‘a particular value’, how will I do it. For eg: update all the document whose values.val1 === ‘apple’
db.operate.updateMany(
{values: {val1: “apple”}},
{$set: {name: “new name”}}
)