🌟CRUD Operation In MongoDB🌟
What is database?
→ Database is structured way to store and access the data.
NoSQL Database: Any data which is organized but not in from of row and column.
MongoDB : It is NoSQL database, In MongoDB data is stored in documents format.
What is Document?
→ Document is a way to store data as set of field-value pairs.
for e.g. : { <field>: <value>,
“name” : “Rahul”,
“age”: 22
}
What is collections?
→ An organized store of documents in MongoDB, usually with common fields between documents.
What is MongoDB Atlas ?
→ Atlas cloud database is fully managed database, built for wide range of applications with MongoDB at its core.
→ Atlas has many tools and services within it that are built specifically for the MongoDB Database.
How does MongoDB stores data?
→ When you view / update document is MongoDB , It is in JSON( JavaScript Object Notation ) .
JSON Format :-
- Start and end with curly braces {}.
- Separate each key and value with a colon (:).
- Separate each key : value pair with a comma (,).
- keys must be surrounded by quotation marks(“ ”).
In MongoDB keys are also called fields.
for e.g. : {
“name” : “Rahul”,
“age”: 22
}
Pros of JSON : It is user friendly, readable and Familiar .
Cons of JSON : It is text-based format, Space Consuming and Supports limited number of basic data types.
Performing CRUD operation :
CRUD → Create, Read, Update and Delete.
C → Create
Create Database :
Syntax:
> use database_name
example : create a database for Smart Phone.
Q. How to insert data in MongoDB?
→ By Insert Operation :
It will add new documents to a collection. If a collection does not exist, the insert operation will create one.
you can see there is no collections in smart_phone database.
Lets see, How to create collection inside database?
whenever we will insert something, that time only it will create a collection and insert documents into it.
Syntax for Insert operation :
> db.collection.insert( { > db.collection.insertOne({
field: value, or field: value,
field: value field: value
} ) } )
for example:
There are two ways to insert document in collections:
- By using insertOne():
→ db.collection.insertOne() command can be used to insert one document at a time.
2. By Using insertMany():
→ db.collection.i nsertMany() can be used for multiple documents insertion into the collection.
Q. How to Insert multiple documents?
→ by using an array([]) :
Syntax :
> db.collection.insert( [ or // db.collection.insertMany( [
{ document 1 },
{ document 2},
......
] )
example:
multiple documents insertion into the collection.
> db.product_catalog.insert([
{
prodid: 7000002,
prodname: “iphone 8”,
manufacturer: “apple”,
categories: {main:”electronics”,sub:”smartphones”},
date_of_launch: new Date(“2017–09–07”),
price: 65000,
colors: [“silver”,”black”,”gold”,”rosegold”]
},
{
prodid: 7000003,
prodname: “iphone 9”,
manufacturer: “apple”,
categories: {main:”electronics”,sub:”smartphones”},
date_of_launch: new Date(“2018–09–07”),
price: 70000,
colors: [“silver”,”black”,”gold”,”rosegold”]
}
])
1st example :
2nd example :
> db.product_catalog.insert (
[
{prodid:7000010,prodname:”nosql distilled”,publisher:”Addison-Wesley”,ISBN:1234567,price:400},
{prodid:7000011,prodname:”big data: principles and best practices”,publisher:”Dreamtech”,price:700}
]
)
Additional Methods for Inserts:
The following methods can also add new documents to a collection:
db.collection.updateOne()
when used with theupsert: true
option.db.collection.updateMany()
when used with theupsert: true
option.db.collection.findAndModify()
when used with theupsert: true
option.db.collection.findOneAndUpdate()
when used with theupsert: true
option.db.collection.findOneAndReplace()
when used with theupsert: true
option.db.collection.bulkWrite()
.
we will discuss these methods later in this blog.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
R → Read :
Q. How to to retrieve documents from the collection ?
→ By using find operation :
Syntax :
> db.collection.find(
{ query criteria },
{ projection criteria }
)
There are two version of find operation :
- findOne(): only one of the best document from collection they will show you.
2. find(): It will show you many documents from collection.
for example:
- Projection: Only view that fields which requires.
Syntax :
> db.collection.find(
{ query criteria },
{ projection criteria }
)1 --> to include that field
0 --> exclude the field(all the field except one)
NOTE: In projection, At a time you can include or exclude , you can’t do both operation in same projection query.(exception in case of _id: 0)
In simple ways, it means:
- {<field 1> : 1, <field 2> : 1} → valid
2. {<field 1> : 0, <field 2> : 0} → valid
3. {<field 1> : 1, <field 2> : 1,_id:0} → valid (Exception)
4.{<field 1> : 1, <field 2> : 0} → Invalid
Retrieve the documents based on criteria :
Q. How to Retrieve the documents having prodname as ‘iphone 8’?
→
>db.product_catalog.find(
{prodname: "iphone 8"}
)
Q. How to Retrieve the documents that either does not contain colors field or null value for that field?
> db.product_catalog.find(
{ colors:null }
)
**** Using existence check:
> db.product_catalog.find(
{ colors: {"$exists":true} }
)
if colors exists then it will retrieve documents otherwise it won’t retrieve documents.
Q. How to retrieve embedded document?
→ embedded document means document inside document.
example :
using . (dot) :
> db.product_catalog.find(
{ “categories.main”:”electronics” }
)
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
U → Update :
Update operation allows users to modify the existing documents in a collection whenever a change occurs. A criteria or filters needs to be specified.
Syntax For updating documents :
MongoDB provides the following methods for updating documents in a collection:
1 . db.collection.updateOne():
Updates at most a single document that match a specified filter even though multiple documents may match the specified filter.
2. db.collection.updateMany():
Update all documents that match a specified filter.
3. db.collection.replaceOne():
Replaces at most a single document that match a specified filter even though multiple documents may match the specified filter.
Examples :
For this practical, I am creating new database names ecommerce and inserting document in it.
> use ecommerce
Now Inserting documents in products collection.
> db.products.insertMany(
[
{prodid:7000010,prodname:”nosql distilled”,publisher:”Addison-Wesley”,ISBN:1234567,price:400},
{prodid:7000011,prodname:”big data: principles and best practices”,publisher:”Dreamtech”,price:700}
{ prodid: 7000001,prodname: "iphone 7",manufacturer:"apple",
categories:{main:"electronics",sub:"smartphones"},
date_of_launch: new Date("2016-09-07"),price: 60000,
colors: ["silver","black","gold","rosegold"]} { prodid: 7000002,prodname: "iphone 8",manufacturer:"apple",
categories:{main:"electronics",sub:"smartphones"},
date_of_launch: new Date("2017-09-07"),price: 65000,
colors: ["silver","black","gold","white"]} ]
)
Update a single document based on condition :
Update the prodname of a book from “nosql distilled” to “NoSQL distilled”.
> db.products.updateOne(
{ prodname : "nosql distilled" },
{ $set : { "name" : "NoSQL distilled" }}
)
You can check whether it updated or not.
*** It is not updated it is inserted because name field was not there previously.:
> db.products.find(
{ prodname : "nosql distilled" }
)
Now, I am updating again ‘name’ → “NoSQL distilled” to “NoSQL”
> db.products.updateOne(
{ prodname : "nosql distilled" },
{ $set : { "name" : "NoSQL" }}
)
no check again it’s updated now :
> db.products.find(
{ prodname : "nosql distilled" }
)
Update a Multiple Embedded document based on condition :
Q. Update sub of categories smart phone to mobile phone based on condition wherever manufacturer is apple.
> db.products.updateMany(
{ "manufacturer": "apple" },
{ $set : { "categories.sub" : "mobile phone" }}
)
You can check whether it updated or not. :
> db.products.find(
{ manufacturer : "apple" }
)
Replace a document based on condition:
> db.products.replaceOne( { “name” : “NoSQL” }, {"name":"Nosql distilled"})
whole data is replaced, you can see in below document :
Now again, I am replacing this document to normal document whatever it was in the beginning.
> db.products.replaceOne(
{name: "Nosql distilled"},
{prodid:7000010,prodname:”nosql distilled”,publisher:”Addison-Wesley”,ISBN:1234567,price:400}
);
You can check again is it replaced back to normal or not :
> db.products.find(
{ prodname : "nosql distilled" }
)
Using upsert to update documents else insert :
The operation updates all the documents with price greater than ‘80000’ and manufacturer ‘apple’. If there are no documents matching the given criteria, a new document would be inserted.
> db.product_catalog.updateMany(
{ “price” : { $gt : 80000 }, “manufacturer” : “apple” },
{ $set: { “prodname” : “iphone 7 plus” } },
{ upsert: true }
)
we can see in ecommerce database :
> db.products.find(
{ manufacturer : "apple" }
)
Field Update Operators :
1. $inc : Increments the value of the field by the specified amount.
example :
Q. Increase the price of the book with ISBN ‘1979891’ by 20:
Before Increasing price :
> db.products.find(
{ ISBN: 1234567}
)
After running query value would be increased so let’s check :
> db.products.update(
{ ISBN: 1234567 },
{ $inc: { price: 20 } }
)
For decreasing the price of ISBN :1234567. we just need to put (-)minus symbol before value.
> db.products.update(
{ ISBN: 1234567 },
{ $inc: { price: -20 } }
)
2. $max : Only updates the field if the specified value is greater than the existing field value.
3. $min : Only updates the field if the specified value is less than the existing field value.
example :
Update the price of the product with ISBN ‘1234567’ to ‘430’ if the given new value is greater than the current value:
> db.products.update(
{ ISBN: 1234567 },
{ $max: { price: 430 } }
)
similarly, you can use $min too.
4. $mul: Multiplies the value of the field by the specified amount.
Multiply the price of the product by ‘2’ of ISBN ‘1234567’ :
db.products.update(
{ ISBN: 1234567 },
{ $mul: { price: 2} }
)
before multiplication :
After multiplication:
5. $rename: Renames a field.
Rename the price field to ‘Rs’ of ISBN ‘1234567’:
> db.products.update(
{ ISBN: 1234567 },
{ $rename: { "price": "Rs"} }
)
Renaming back ‘Rs’ to ‘price’:
6. $unset: Removes the specified field from a document.
let’s remove the price from the document with ISBN ‘1234567’:
> db.products.update(
{ ISBN: 1234567 },
{ $unset: { "price": ""} }
)
7. Again you can set price by $set operator:
> db.products.update(
{ ISBN: 1234567 },
{ $set: { "price": 400} }
)
Array Update Operators :
- dataset for array operator :
> use student
then insert these documents to student database in students collection.
> db.students.insertMany( [
{ “_id” : 1, “grades” : [ 85, 80, 80 ] },
{ “_id” : 2, “grades” : [ 88, 90, 92 ] },
{ “_id” : 3, “grades” : [ 85, 100, 90 ] }
] )
1. $ : Acts as a placeholder to update the first element that matches the query condition.
Syntax :
{ "<array>.$" : value }
Example :
To update the first element whose value is 80
to 82
in the in the grades
array, use the positional $
operator if you do not know the position of the element in the array:
> db.students.updateOne(
{ _id: 1, grades: 80 },
{ $set: { "grades.$" : 82 } }
)
Before :
After running query :
if you want to change all 80
to 82
then use $[]
operator. lets see example in next section.
2. $[]: Acts as a placeholder to update all elements in an array for the documents that match the query condition.
Syntax :
{ "<array>.$[]" : value }
Example :
- Set all value of _id:2 are 80 by using $[] operator.
> db.students.updateOne(
{ _id: 2 },
{ $set: { “grades.$[]” : 80 } }
)
Q. To update the All the element whose value is 80
to 82
in the in the grades
array, use the positional $[]
operator if you do not know the position of the element in the array:
> db.students.updateOne(
{ _id: 1, grades: 80 },
{ $set: { "grades.$[]" : 82} }
)
3. $[<identifier>]: Acts as a placeholder to update all elements that match the
arrayFilters
condition for the documents that match the query condition.
Syntax:
> db.collection.updateMany(
{ <query conditions> },
{ <update operator>: { “<array>.$[<identifier>]” : value } },
{ arrayFilters: [ { <identifier>: <condition> } ] }
)
Q.To update all elements that are greater than or equal to 85
in the grades
array, use the filtered positional operator $[<identifier>]
with the arrayFilters.
> db.students.updateMany(
{ },
{ $set: { “grades.$[element]” : 100 } },
{ arrayFilters: [ { “element”: { $gte: 85} } ] }
)
*** In this operator if query is not satisfied(no such document found). then it will upsert the document.
4.$addToSet: Adds elements to an array only if they do not already exist in the set.
Syntax:
> { $addToSet: { <field1>: <value1>, … } }
Example : -
We will use ecommerce database and products collections:
>use ecommerce
then you can see, some of colors of iphone 7 is already exist in colors array field.
I am adding ‘pink’ in colors array field by using $addToSet operator.
> db.products.update({“prodname”: “iphone 7”},{$addToSet:{colors:’pink’}})
5. $pop: Removes the first or last item of an array.
Syntax:
> { $pop: { <field>: <-1 | 1>, … } }-1 --> for first item of array.
1 --> for last item of array.
example :
Removing First colors of iphone 7:
> db.products.update({“prodname”: “iphone 7”},{$pop:{colors:-1}})
Removing last colors of iphone 7.
> db.products.update({“prodname”: “iphone 7”},{$pop:{colors:1}})
6. $push: Adds an item to an array.
The $push
operator appends a specified value to an array.
Syntax:
> { $push: { <field1>: <value1>, … } }
Example:
Appending ‘blue’ in colors of iphone 7:
> db.products.update({“prodname”: “iphone 7”},
{$push:{colors:"blue"}})
7. $pull: Removes all array elements that match a specified query.
Syntax:
> { $pull: { <field1>: <value|condition>, <field2>: <value|condition>, … } }
Example: -
Pulling “black” and “gold” from colors array of iphone 7:
> db.products.updateOne( { “prodname”: “iphone 7”}, { $pull: { colors: { $in: [ "black", "gold" ] } } })
8. $pullAll: Removes all matching values from an array.
The $pullAll
operator removes all instances of the specified values from an existing array. Unlike the $pull
operator that removes elements by specifying a query, $pullAll
removes elements that match the listed values.
Syntax:
>{ $pullAll: { <field1>: [ <value1>, <value2> … ], … } }
Example:
> db.products.update( { “prodname”: “iphone 7”}, { $pullAll: { colors: [ “blue”, “rosegold” ] } } })
D for Delete
Delete Operation:
Delete operation allows you to delete the documents from a collection that is no longer valid. You can specify criteria or filters to delete documents.
- MongoDB provides following methods for delete document :
- db.collection.deleteOne(): Delete at most a single document that match a specified filter even though multiple documents may match the specified filter.
Example:
Delete Only One Document that Matches a Condition :
- for this operation, we will using ecommerce database and products collection.
> use ecommerce
you can see products collection have this much documents.
> db.products.find({})
Q. Delete a document from products collection where “prodname” is “iphone 7”.
> db.products.deleteOne({prodname:iphone7})
After deleting document, you can see the collection again, it’s deleted.
2. db.collection.deleteMany(): Delete all documents that match a specified filter.
example:
Delete All Documents that Match a Condition:
Q. Delete a document from products collection where “manufacturer” is “apple”.
> db.produts.deleteMany({"manufacturer":"apple"})
let’s see this practically:
before the collection was like that.
After deleting the all the document where “manufacturer” is
“apple”.
> db.produts.deleteMany({"manufacturer":"apple"})
Delete All Documents:
- To delete all documents from a collection, pass an empty filter document
{}
to thedb.collection.deleteMany()
method.
> db.products.deleteMany({})
3. db.collection.remove(): Delete a single document or all documents that match a specified filter.
Normal Syntax:
> db.collection.remove( <query>, <justOne>)
Syntax:
> db.collection.remove( <query>,
{ justOne: <boolean>,
writeConcern: <document>,
collation: <document>,
let: <document> // Added in MongoDB 5.0
}
- Delete a single document from collection with matching query :
> db.collection.remove( <query>, true )
- Delete all the document from collection with matching query:
> db.collection.remove( <query>)
- Delete all the document from collection:
> db.collection.remove({})
IF you want to know more about operators then you can read this blog.
Thank you….