MongoDB is one of the widely used NoSQL databases. You can read SQL vs NoSQL databases where I have explained the difference between SQL and NoSQL databases.
In this tutorial, I will be explaining CRUD (aka create, read, update and delete) operations on MongoDB. I will keep this short and simple.
Let’s begin with an overview of each MongoDB method.
Table of Contents
To create one or more documents, there are two popular methods used.
Use this method to insert a single document in the collection.
Syntax:
db.collection.insertOne(data, options)
Use this method to insert more than one document in the collection at a time.
Syntax:
db.collection.insertMany(data, options)
To read the document from the MongoDB collections here are some of the methods you can use.
Use this method to retrieve the first matching document for the mentioned filtering criteria.
Syntax:
db.collection.findOne(filter, options)
Note: The concept of the cursor can not be applied here.
Use this method to find and retrieve multiple (or all) matching documents at once based on the filtering criteria.
Syntax:
db.collection.find(filter, options)
This method actually returns a cursor object along with some metadata.
To update the document in the MongoDB collection, you can use the following methods.
It is used to update a single document in the collection that satisfies the given criteria.
Syntax:
db.collection.updateOne(criteria, data, options)
It is used to update multiple documents in the collection that satisfy the given criteria.
Syntax:
db.collection.updateMany(criteria, data, options)
Note: If you specify empty braces {} as criteria, all documents will be updated with given data. Be careful if you while executing this command.
By default, it updates a single document in the collection. If you wish to update the multiple documents you need to specify {multi: true}
.
As we have updateOne()
and updateMany()
to update one and multiple documents in the collections, respectively. You can avoid this method.
It is used to replace a single document in the collection that satisfies the given criteria.
Syntax:
db.collection.replaceOne(criteria, newData, options)
Use the below methods to delete the documents from the MongoDB database collection.
Use this method to delete the first document satisfying the given criteria.
Syntax:
db.collection.deleteOne(criteria, options)
Use this method to delete more than one document satisfying the given filtering criteria.
Syntax:
db.collection.deleteMany(criteria, options)
Note: If you specify empty braces {}
as criteria, all documents will be deleted.
MongoDB is getting more popular now a day, just as MySQL. Both are used for a different purpose. Read MongoDB vs MySQL.
Besides the above-mentioned methods, there are couple more methods provided by MongoDB such as findOneAndReplace()
, findOneAndUpdate()
etc. The above-mentioned are the basic methods everyone should be aware of.
Any doubt or point to discuss? Let’s write in the comment section below.