This article covers CRUD operations in MongoDB.
Prerequisites
- MongoDB installed on your computer - Install MongoDB
- Familiarity working with the terminal
Introduction
MongoDB is a structured NoSQL document database. Structured means that just like other databases, MongoDB stores data in an organised way. A NoSQL database means MongoDB does not store data in related tables comprised of rows and columns. Instead, MongoDB stores data in documents which are in turn stored in collections that are stored in databases.
A document is a way to store and organise data in the form of key-value pairs. This format is called JSON format which is based on Javascript objects. An example of a document is shown below:
{
"name": “John Doe”,
"home": “Wisconsin”,
"age": 20,
"isTall": true,
"occupation": “student”
}
On the left of the colon are keys/fields and on the right of the colon are values. Keys uniquely identify a data point. Keys can be wrapped in quotation marks or written without them. The values are the data related to the identifiers used as the keys. If the value stored is a string, it has to be wrapped in quotation marks.
A collection is an organised way to store documents in a MongoDB database. A MongoDB database can have many collections. A collection can store many documents.
CRUD operations
Create Read Update Delete(CRUD) are the main operations you will use to interact with a MongoDB database and manage the data stored in it.
- Create operations involve writing data to the database by inserting documents.
- Read operations involve querying data stored in the database
- Update operations involve modifying or changing data in the database
- Delete operations involve permanently removing data from the database
Getting started
With MongoDB already installed in your system open your terminal window and follow the following steps to start and run MongoDB in Ubuntu:
- For windows systems visit Install and run MongoDB
- For macOS visit Install and run MongoDB
- Confirm MongoDB has been installed in your system by executing the following command to check for the version installed:
If MongoDB is successfully installed in your system you should see an output such asmongod --version
db version v6.0.3
which shows the version of MongoDB installed. If the terminal output says the command is not recognised visit Install MongoDB to install MongoDB in your system. - Start a MongoDB server
sudo systemctl start mongod
- Verify MongoDB has started successfully
If your MongoDB server started successfully you should receive such an output indicating that your MongoDB server is active and running. Presssudo systemctl status mongod
CTRL + C
to go back to typing in the terminal - Begin using MongoDB by executing
This should take you to such a window where you will execute MongoDB Shell commandsmongosh
Create operations
These are operations that involve inserting data into the database. To do this, you need to create a database to store collections where documents will be stored.
To see the databases available on your computer, execute show dbs
in the terminal. By default there will be three existing databases, namely admin,config and local which store metadata. You won't need to modify anything in these databases.
To start using a particular database, execute use <database_name>
. If you execute this command for a database that does not exist, the database is implicitly created by MongoDB.
Therefore, use this command to create and navigate into a database called shop
use shop
If you execute
show dbs
at this point, you won't see the database shop listed. This is because MongoDB only shows databases with collections in them. Essentially, it shows databases with data stored in them.
To add documents to a collection, you have two options available: insertOne() to insert one document at a time and insertMany() to insert multiple documents into a collection in one go.
The syntax for the above commands are:
- db.collectionName.insertOne({document_to_insert})
- db.collectionName.insertMany([{document1}, {document2}, {document3} ....])
Just like with a database, when you insert a document into a collection that does not exist, the collection gets created for you automatically.
To insert one document into a collection called products, execute the following command:
db.products.insertOne({name: "cheese", price: 13.55, isAvailable: true, supplier: "gilmann"})
Upon successful insertion you should get such an acknowledgement in the terminal:
{
acknowledged: true,
insertedId: ObjectId("637b893b6ad1378b10cb4ef3")
}
After inserting this document, executing
show dbs
will show the shop database just added. Executingshow collections
will show the products collection added in the shop database.
All documents stored in MongoDB have a unique _id field which is used to uniquely identify a document. You can set this field yourself. However, if you insert a document without a unique _id field, MongoDB automatically sets it for you.
To insert multiple documents at once, we use insertMany(). To insert multiple documents at once, they must be wrapped in an array using [ ] like so:
db.insertMany([{document1},{document2},{document3}...])
Execute the following command to insert multiple documents into the products collection
db.products.insertMany([{name: "bag", price: 30.99, isAvailable: true, supplier: "gucci"}, {name: "shoe", price: 100.43, isAvailable: false, description: {brand: "nike", size: 40}}])
Read Operations
These operations allow you to query the database and get documents that match a specified criteria. For read operations, find() and findOne() are used.
The syntax for these operations are:
- db.collectionName.find({query1}, {query2})
- db.collectionName.findOne({query1}, {query2})
You can have one or more queries in the find() and findOne() methods.
find() is used to get all documents that satisfy a given query while findOne() is used to find a single document that satisfies the given query. If findOne() is used and several documents meet the passed query, the first document that matches the query is returned. If no documents meet the passed criteria, null is returned
To see all documents in a collection, execute find() without passing any query to it. Execute the following command to see all documents in the products collection
db.products.find()
The following output is returned showing all documents in the products collection
[
{
_id: ObjectId("637b893b6ad1378b10cb4ef3"),
name: 'cheese',
price: 13.55,
isAvailable: true,
supplier: 'gilmann'
},
{
_id: ObjectId("637b8bf26ad1378b10cb4ef5"),
name: 'bag',
price: 30.99,
isAvailable: true,
supplier: 'gucci'
},
{
_id: ObjectId("637b8bf26ad1378b10cb4ef6"),
name: 'shoe',
price: 100.43,
isAvailable: false,
description: { brand: 'nike', size: 40 }
}
]
Notice the _id field that was automatically added to the documents in the collection. This field uniquely identifies the documents in the collection The
find()
command returns a cursor that shows the first 20 documents in a collection. If your collection has more than 20 documents, only the first 20 will be displayed. To see the next 20 documents in the collection, execute the commandit
in the terminal.it
stands for iterate.
To find all documents in the product collection where name
is set tocheese
execute the following command
db.products.find({name: 'cheese'})
This returns
[
{
_id: ObjectId("637b893b6ad1378b10cb4ef3"),
name: 'cheese',
price: 13.55,
isAvailable: true,
supplier: 'gilmann'
}
]
To find the number of documents that satisfy your query, use count()
db.products.find({name: 'cheese'}).count()
This returns 1
To find a single document that satisfies a given criterion in a collection, such as a document in the products collection whose value for isAvailable
is set to true
, execute:
db.products.findOne({isAvailable: true})
This returns
{
_id: ObjectId("637b893b6ad1378b10cb4ef3"),
name: 'cheese',
price: 13.55,
isAvailable: true,
supplier: 'gilmann'
}
even though two documents have isAvailable
set to true
Update operations
These are operations done to modify the documents already stored in the collection. To do this, we use updateOne(), updateMany() and replaceOne(). To use update documents using updateOne() and updateMany() you need to also use MongoDB update operators which are used to perform different update operations.
This guide will use the update operators $set
and $inc
. Visit MongoDB Update Operators to read about other update operators.
The syntax for the three methods is similar and a sample updateOne() method is shown below
updateOne() is used to update a single document that matches the specified query To update the value of a field in a single document use, updateOne()
db.products.updateOne({name:"cheese"}, {"$set": {price: 30.55}})
$set is an update operator that updates the value of the specified field with a new specified value. If you update a non-existent field, the field is implicitly created
updateMany() is used to update all documents that satisfy the specified query.
Execute the following command to increment the prices of all documents where isAvailable
is set to true
. This operation will increment the prices by 10
db.products.updateMany({isAvailable: true}, {"$inc":{price:10}})
$inc is an update operator that increments the value of numerical values by the specified amount amount
replaceOne() is used to replace an entire single document in a collection. After this method is executed, the old document is lost and replaced with the new document passed in the replaceOne()
method. If the new document passed does not have fields similar to the original document, the fields and values in the original document will be lost. The only field that remains the same is the _id field unless you explicitly change it in the new document. **replaceOne() does not need any update operator.
Execute the following command to replace a document with name
set to bag
with a new document
db.products.replaceOne({name: 'bag'}, {fish: 'salmon', quantity: '400'})
Unlike other documents in the products collection, the newly replaced document has a different structure compared to the earlier ones. MongoDB is flexible and documents in a collection do not need to have the same structure. You can store two completely different documents in the same collection.
Delete Operations
These are operations for deleting documents from a collection. The methods for deleting documents from a collection are deleteOne() and deleteMany(). You can pass a query to these methods to specify which document you want to delete.
deleteOne() is used to delete the first document that matches a given query
Execute the following command to delete a document where the field isAvailable
is set to false
db.products.deleteOne({isAvailable:false})
This deletes the product with the name
field set to shoe
deleteMany() is used to delete all documents that match a given query. Just like in deleteOne() you can pass a query to it, to delete all documents that match the query. However, if you execute deleteMany() with an empty query, all documents in the collection will be deleted. Execute the following command to delete all documents in the products collection
db.products.deleteMany({})
To delete a collection use the drop() method. Execute the following command to delete the products collection from the shop database
db.products.drop()
upon successful deletion, the terminal returns true
Once a database has no collections in it, it is deleted/dropped by MongoDB. However, to delete a database yourself, for instance, a database called shop, navigate to the database by executing
use shop
then execute
db.dropDatabase()
If you're already in the database, you can simply execute db.dropDatabase
to delete the entire database.