Introduction to MongoDB
A beginner’s guide.
Introduction To Database
A database is a collection of related data and a database management system is the software that manages the database. The database management system is abbreviated as DBMS. DBMS carries out all the operations related to data such as creating, reading, updating, and deleting data. There are mainly two types of databases. NoSQL (Not Only SQL) and SQL (Structured Query Language).
- NoSQL: NoSQL or non-relational is a type of database that stores semi-structured data like XML as well as unstructured data like JSON, unlike SQL which stores only structured data. It can handle relational databases but can also handle more complex data structures. Different NoSQL DBMS store records in different forms such as documents, key-value pairs, graphs, objects, and columns depending on the DBMS. Following is the mapping of some databases with the type in which they store the record
- MongoDB: Document-oriented
- Redis: Key-Value pairs
- Neo4j : Graph-based
- Apache Cassandra: Column-family
- db4o: Object-based
What is MongoDB
MongoDB is an open-source, non-relational database and a database management system that stores data in flexible and unstructured JSON documents. It is commonly used in a wide range of applications, including web applications, mobile backend, content management systems, etc. Below is an example of a document in MongoDB.
Terminologies related to MongoDB.
- Document — A single data record is called a document. In the above image, the object/map within the array is an example of a single document.
- Collection — A group of documents is called a collection. It is a container for records. In the above example,
users
is the collection name that contains the multiple records. - Database — A group of related collections is called a Database. It is a container for one or more collections. In above example
test
is the database that contains the collectionusers
. - field — Field refers to the key in a key-value pair of a document. The above document contains various fields like
_id
,name
,age
,profession
andemail
. - Document Id — Every document in MongoDB has a
_id
field which is called the document ID. This is an autogenerated field that helps to uniquely identify the records.
Prerequisite
MongoDB — MongoDB should be installed and set up on your computer. If not, you can follow this guide and download the MongoDB community edition.
MongoShell — It is a shell provided by MongoDB to execute MongoDB commands, it comes along with the installation of MongoDB. Make sure either mongosh.exe
or mongo.exe
is present in the bin directory of MongoDB. If in any case this file is not present in the directory, download it from here and add the files to the bin folder of mongodb.
Setup and Database Commands
In this section, we will set up our computer to execute MongoDB commands and run some basic commands related to the database.
- Setup:
- Open the terminal and execute
mongod
. This command will start the MongoDB server and allow clients to connect to it and interact with the database. - Open another terminal and execute
mongosh
. This command will activate the MongoDB shell. After executing the command you will get output similar to the below image where we can execute other commands.
Note: Ifmongosh
does not activate the shell usemongo
.
- Commands related to database.
- List all the databases: The
show dbs
command is used to list all the databases present in MongoDB. The admin, config, and local databases are present in MongoDB by default. In the below imagetest>
is the name of the database in current use
2. Create a database: The use <db>
command where <db>
is the name of the database, used to create a new database. This command checks if a database already exists. If it does, it switches to that database. If not, it creates a new one and then switches to it.
3. Delete a database: To delete a database, make sure you are using the database that you want to delete and then run db.dropDatabase()
method to delete the database. As shown below we deleted the app
database and then switched to the test
database and listed all the databases present in MongoDB to confirm that app
database does not exist.
Collection Operations and Commands
Collections are containers to store a group of documents. Following are the commands related to collections:
1. Create a new collection: db.createCollection(‘your_collection_name’)
The createCollection()
method is used to create a new collection in the database. In the below example, we create a collection named users
2. List all the collections of the database:
Similar to the show dbs
command, the show collections
command is used to list all the collections of a database. In the below example, the output of the command lists only one collection named users that we created in the previous step.
3. Delete collection:
To delete a collection run db.<collection_name>.drop()
method. As shown below, we deleted the users
collection and then listed all the collections present in the app
database but there are none as users
was the only collection that was present in the app
database.
CRUD operations for documents
Create Documents
- Insert a document:
db.<collection_name>.insertOne()
The insertOne()
method is used to add one document to the collection. A json object is passed to the insertOne()
method which stores it in the database. As shown in the below example, we store user data in the users
collection and it returns a JSON object output which contains the _id field value of the inserted document.
2. Insert Many documents: db.<collection_name>.insertMany()
The insertMany()
method works the same as insertOne()
but this method can insert multiple documents at a time. It takes an array of JSON objects as input, stores those documents in the database, and returns a JSON object that contains an array of IDs of the inserted documents.
3. Insert an embedded Document:
An embedded document is a document with nested JSON objects. As shown in the below example, the address fields have a value of JSON object that has fields, home_address
and street_address
. We can insert these documents with the same methods, that is insertOne()
or insertMany()
. You can nest any number of documents that fits your data modeling needs.
- Find or Query documents
- Find one or more documents:
db.<collection_name>.find({query})
Thefind()
method is used to search documents from the collection. It takes a valid JSON query as an optional argument, as shown below, the{age: 25}
is the query passed to the method. It returns all documents that have an age value of 25. If no query is passed to thefind()
method then it returns all the documents from the collection.
2. Find only one document: db.<collection_name>.findOne()
The find method returns only one method that matches the query first.
3. Find with projection: db.<collection_name>.find({query}, {projection})
Projection refers to the process of specifying or rejecting which fields should be present in the returned document. In MongoDB, we can specify this by adding a json object after the query object in the find()
and findOne()
method. The projection JSON object consists of field names and 1 or 0 as their values. 1 includes the field in the result and 0 excludes the field from the result.
Excluding _id
field in the return document:
When we do not specify any fields in the projection object, it includes all the fields by default, but when we include atleast one field in the projection object, all the other fields are excluded except those that are included in the projection object and _id
field, hence you don’t need to include the _id
field explicitly as it will always be included. If you don’t want _id
field in the result you can exclude it explicitly as shown below by assigning it the value 0.
4. Limit the number of return documents:db.<collection_name>.find().limit(number)
The limit() method helps us control how many documents we want to receive as a result. When we use it with the find() method and specify a limit, it finds documents based on a query and only returns the specified number of documents from the DB.
5. Sort the documents based on a particular field:db.<collection_name>.find({query}).sort({sort_object})
The sort method is used to sort the documents in ascending or descending order based on a particular field. The projection JSON object consists of a field name and 1
or -1
as their values, 1 for ascending order, and -1 for descending order. As shown in the below example, we have sorted the documents based on the age of the user in descending order and limited the result to 3 using the limit method.
Query document based on the embedded document key.
We can access an embedded document key using the dot .
operator. In the below example, the address field makes the document an embedded document as it contains JSON object as the value. we can access address fields using the dot operator such as address.home_address
or address.street _address
and use it in the query.
- Update documents
- Update One document:
db.<collection_name>.updateOne({query}, {update_object})
The updateOne()
method is used to update the first document that matches the query. In the below example, the query object searches for a document that has a name equal to Neron Farquharson, and it then $set
operator of MongoDB that is used to set any field value to a new updated value. There are different operators in MongoDB for different operations, you can find a link here. The below example set the name field to Noah Kevin.
2. Update many documents: db.<collection_name>.updateMany({query},{update_object})
The updateMany()
method is used to update more than one record at once. In the below example, all the records that have an age equal to 25 are set to 29. In the response, you can see the modifiedCount
is equal to 2 which means 2 records are updated.
3. Replace an entire document: db.<collection_name>.replaceOne({query},{record})
The update methods just updates the specified fields from the document but the replaceOne()
method replaces the entire document with the new one except the _id
value.
4. Remove a field from the document:
We can use the $unset
operator in the update methods to remove a field by setting its value to “”
. In the below example, we remove the address key embedded object key street_address
from a document whose email is emily@gmail.com
5. Increment the value of a key:
To increase a value by a specific number we can use $inc
operator and specify the field whose value needs to be incremented and the value by which it should be incremented. In the below example, we have increased the age of the record whose email is abc@gmail.com
by 4 value.
6. Adding array as value and pushing a new item to it:
A key can store an array as the value in MongoDB. In the below example first, we have set a new key named hobbies
to the record that has an email equal to abc@gmail.com
. Then we can use the $push
operator to add one more element, example: badminton to the hobbies key.
- Delete documents
- Delete one document:
db.<collection_name>.deleteOne({query})
The deleteOne()
method deletes the first document from the collection that matches the query. In the below example, we are deleting the record whose name key value is equal to ‘Bob Builder’
.
2. Delete many documents:
The deleteMany()
method deletes all the documents that match the query condition. In the below example, we have used the $gt
operator which is a conditional operator for greater than
. This deletes all the records that have an age greater than 25. As a result, this command deletes 3 records since the deletedCount
in the resultant object is 3.
Conclusion:
In this article, we have learned different MongoDB commands and methods to perform operations on databases, collections, and documents. In the next article, we will see how to implement the CRUD operations using MongoDB as a database with a NodeJS and express application.
My name is Alfiya Siddique, I am a 3rd-year diploma student studying Computer Science and a Backend Developer Intern. You can follow me on Linkedin and Twitter.
Thank you for your time, hope you find this article helpful. Have a great day ahead!