How to Insert, Update, Delete Elements in MongoDB

here are the kive examples so that you can easily understand the query execution in MongoDB

db.customers.find().pretty();

find using filters

db.customers.find({name:"Suraj"}).pretty();

As an array

db.customers.find({name:"Suraj"}).toArray();

find using greater than the value

/* $gt is use for grater and $lt is use for less than */
db.customers.find({age:{$gt:20}})

delete data from document deleteOne

db.customers.deleteOne({name:"Amit"})

same idea logy for multiple deletions  deleteMany

db.customers.deleteMany({name:"Suraj"})

for update we use updateMany, updateOne, replaceOne, update(not recommend)

Now we will see how to update age which was 29 to something else

db.customers.updateMany({age:29},{$set:{age:22}})

now check

replaceOne, and update use set of object data and not use $set 

simply update will replace the data having data to change . Let us see an example with object ID of Amit panchal above

result 

here we can see index name,age removed totally from json. A complete new object data store . This will override our data in database.
Hence we use replaceOne method 

db.customers.replaceOne({name1:"Hi I am Amit PAnchal"},{name:"Amit Panchal",age:22}) 

and view 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codeforbetter will use the information you provide on this form to be in touch with you and to provide updates and marketing.