MongoDB stores data in BSON – Binary encoded JSON documents which supports 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 that is described below and a data structure formed of field and value pairs.
MongoDB CRUD Operations
CRUD operations refer to the basic Create(Insert), Read, Update and Delete operations.
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.
Now, switch to an existing database or create a new Mongodb database using the following command.
use crud
So, we switched to that database.
Now, create a collection using the following command. Finally, let us call the collection operate.
db.createCollection("operate")
So, 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 add new documents to the collection. If the collection does not currently exist, then insert operations will create the collection.
The command db.collection.insert() will perform the insert operation into the collection of the document.
db.operate.insert({ enrollno: "110470116021", name: "Krunal Lathiya", college: "VVP Engineering College", course: { courseName: "BE IT", duration: "4 Years" }, address: { city: "Rajkot", state: "Gujarat", country: "India" } })
It will insert a document in MongoDB.
You can check it by fetching that document using this query.
db.operate.find().pretty()
# Insert Multiple Documents in MongoDB
MongoDB provides us the following methods to insert the documents into a collection.
- db.collection.insertMany()
The syntax is following.
db.collection.insertMany( [ <document 1> , <document 2>, ... ], { writeConcern: <document>, ordered: <boolean> } )
It returns the following document containing:
- A boolean 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 documents.
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 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 that identify 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 modify existing documents in the collection. MongoDB provides us the following methods to update the documents of the collection.
- db.collection.updateOne()
- db.collection.updateMany()
- db.collection.replaceOne()
You can write the update query in MongoDB like below.
db.operate.updateOne( { name: "Rushikesh Vekariya" }, { $set: {college: "Marwadi"} } )
In MongoDB, the update operations target the single collection. All the write operations in MongoDB are atomic on the level of the single document.
We can also run an update on many documents like the following.
db.operate.updateMany( { name: "Krunal Lathiya" }, { $set: {city: "Jetpur"} } )
In the operate collection, we have two documents whose name is Krunal Lathiya, so that it will update both the 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 deleteMany function, which deletes all the documents with the provided name.
That’s it for this tutorial.
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”}}
)