MongoDB Tutorial for Beginners | Learn with Examples

In this MongoDB tutorial for beginners, we will cover the basics of MongoDB including NoSQL, advantages, architecture, installation, creating a database and collection, inserting data, reading data, updating, deleting data, and many more operations.

Also, every MongoDB examples explained in this tutorial are all straightforward, elementary, and simple enough for beginners who are hoping to learn about MongoDB. All the examples are very well illustrated and executable with the current version of MongoDB.

Note: In case you can’t find the MongoDB examples you are looking for on this tutorial page, I would recommend using the Search option from the menu bar to find your example code, there are hundreds of tutorials in MongoDB on this website you can learn from.

Related:

1. Introduction to MongoDB

MongoDB is a Document-oriented NoSQL storage system that is well-known and open-source. It is designed to deal with large amounts of data and provides flexibility and scalability for managing data.

MongoDB stores data in JSON-like documents with dynamic schemas, which means that data can be stored in a way that is natural to the application and can be easily modified as the application evolves. Moreover, it also supports rich queries, indexing, and aggregation operations, making it a powerful tool for data analysis and reporting.

In addition to its core functionality, MongoDB offers some tools and features for administering and keeping track of MongoDB deployments, such as the web-based MongoDB Compass GUI and the mongo shell command-line interface.

2. What is NoSQL Database

As we have mentioned that MongoDB is a NoSQL database. NoSQL is an acronym for “not only SQL” which is a kind of database management system (DBMS) that enables flexible and scalable data storage and retrieval without depending on the conventional tabular relations used in relational database management systems. (RDBMS).

NoSQL databases are frequently used for the storage and management of sizable amounts of unstructured or semi-structured data, such as that found in social media, sensor data, and machine logs, which do not easily fit into the rigid RDBMS framework. Additionally, they are frequently employed in real-time web apps that need high availability and scalability.

3. Advantages of MongoDB

Following are the advantages of MongoDB.

  • MongoDB is a flexible NoSQL database that can deal with different types of data and schemas.
  • Its document model allows for easy and fast data access and manipulation.
  • MongoDB scales horizontally through sharing, allowing it to handle large amounts of data.
  • In comparison to conventional SQL, MongoDB is a powerful query language that enables complex queries, joins, and aggregations and makes it possible to query data more naturally.
  • It has a vibrant and active community and is widely adopted by many organizations.

4. Architecture of MongoDB

MongoDB’s architecture is designed to be highly flexible and scalable, making it well-suited for a wide range of data-intensive applications.

Client: Applications connect to MongoDB using client libraries, which give users a method to link to the database, send commands and queries, and receive results.

Servers: MongoDB servers maintain and control the data. Multiple databases can be operated on each server, and numerous collections can exist in each database.

Sharding: Through sharding, MongoDB is capable of horizontal scaling across multiple machines. A shard key, which is a field or collection of fields that determine how data is distributed across shards, is used to partition data across numerous servers during the process of sharding.

Replication: MongoDB supports the automatic replication of data across multiple servers for high availability and fault tolerance. Replication involves maintaining multiple copies of data across servers in a replica set, which ensures that the data is available even in the event of hardware or network failures.

Storage engine: The storage engine of MongoDB is designed to provide high performance and efficiency by using techniques like compression and memory mapping.

Indexing: Indexing optimizes query performance including single-field indexes, compound indexes, and geospatial indexes.

5. Installation of MongoDB

5.1 Download & Install

In this section of the MongoDB tutorial, we will walk through the step-by-step beginner’s installation of MongoDB on your system. First, we have to visit the official website of MongoDB and click on the Download button for the latest version of the MongoDB Community Server. Furthermore, we can select the appropriate version of the MongoDB Community Server installer for the Windows operating system (64-bit or 32-bit).

MongoDB  Beginners Tutorial

Open the setup file after the download is complete, then follow the on-screen instructions to install MongoDB on the Windows computer. We have to set the default location as C:\Program Files\MongoDB\6.0.5, but we can choose a different location according to preference. On completion, we can see all the MongoDB executable files in the specified bin directory. This completes the installation of MongoDB, with this you should able to run the examples explained in this beginners tutorial

MongoDB  Beginners Tutorial

5.2 Start Service

Now, we established the executable file’s environment variable, so we won’t need to alter the path setting each time we want to run it. Open the environment variable on the system and specify the path to the system variable as highlighted in the following image. This allows you to run mongo commands from any path.

download & install

Here, the path has been set for the MongoDB server. Furthermore, we can verify whether MongoDB is installed properly in the system. For this, we have executed the command mongos --version in the prompt which shows the version of the MongoDB.

MongoDB  Beginners Tutorial

Now, let’s interact with MongoDB using the MongoDB shell. As the mongo shell has been superseded by the mongosh shell. So, we have to install mongosh shell from the official website in our system to connect with MongoDB. Once the installation has been done then we can specify the path of the mongosh shell on the prompt like this and automatically connect to the mongosh shell.

MongoDB  Beginners Tutorial

Alternatively, you can also Run MongoDB in a Docker Container.

Related:

6. Create MongoDB Database and Collections

Instead of using tables with rows and columns, MongoDB stores data in flexible, JSON-like documents that can have varying structures and fields. All the documents are stored in the collection.

First, we need to create a new MongoDB database, we have to use the use command followed by the name of the database we want to create. For example, to create a database called MyFirstDatabase, type the following command.


#Creating MongoDB databse
use MyFirstDatabase
create mongodb tutorial

Note that this command only changes the context, If you enter the show dbs command, the result doesn’t show the database created. MongoDB only creates the database when you first store a collection or a document in the database.

So, let’s create the collection in the database MyFirstDatabase by using the command given below.


# Create collection
db.createCollection(“student”)

This will create the collection student into the database MyFirstDatabase as shown in the following image.

We can verify that the collection was created successfully by running the below command to see a list of all collections in the current database.


#Viewing list of collections
show collections

As shown the MongoDB collection student is now created.

7. Insert Documents into MongoDB Collection

In order to insert the documents into a MongoDB collection using the MongoDB Shell, we can use the insertOne() or insertMany() method. Here we have inserted one document using the insertOne() method into the collection student created above.


#Inserting documents to Collection
db.student.insertOne({ _id: 1, name: "Alice",  age: 23 });

The document is inserted here.

MongoDB  Beginners Tutorial

Similarly, if we want to insert multiple documents at once, we can use the insertMany() method of MongoDB. Here, we have inserted three more documents into the collection student.


#Inserting multiple documents to Collection
db.student.insertMany([
  { _id: 2, name: "Ian", age: 21 },
  { _id: 3, name: "Candice", age: 20  },
  { _id: 4, name: "Emily", age: 22  },
]);
MongoDB  Beginners Tutorial

Other examples of inserting documents into MongoDB

8. Read documents from the MongoDB collection

Once the documents are inserted into the MongoDB collection, we can read these documents by performing the MongoDB operation. Reading data in MongoDB is done through the use of the db.collection.find() method. This method allows us to retrieve data from a collection based on a query.

Related: Use findOne() to retrieve the single document.

For example, using the find command like this retrieve all the documents from the collection student.


#Reading documents from collection
db.student.find();

Hence, we can see the documents inserted in the collection.

MongoDB  Beginners Tutorial

However, if we want to read the specific document then we add a query to find() to filter the results. For example, we have to read the document with the field name whose value is Emily. The query will be given like this.


#Reading specific document
db.student.find({ name: "Alice" });

The filtered document is shown in the output.

MongoDB  Beginners Tutorial

Other most used examples to query MongoDB

9. Update Documents in the MongoDB collection

In this section of the MongoDB learners tutorial, I will cover how to modify or update the documents of the collection. To do so, the updateOne() or updateMany() methods are used for updating the documents in MongoDB.

To update a single document, use the updateOne() method and pass in the query. Here, we have updated the document by following this query.


#Updating Documents
db.student.updateOne(
  { name: "Emily" },
  { $set: { age: 24 } }
);

The results ensure that the single document is updated.

Finally, the document is updated with the new value set to the field.

MongoDB  Beginners Tutorial

In the same manner, update multiple documents using the insertMany() method. Here is the insertMany() query which updates the multiple documents of the collection student.


# Update multiple documents
db.student.updateMany(
  { age: { $gte: 20 } },
  { $set: { name: "Students" } }
);

The documents that satisfied the filter object are updated now.

Other most used examples of updating documents

10. Delete Documents in the MongoDB collection

After the creation, reading, and updating operations of MongoDB. The next operation is to delete the data from the documents of the MongoDB collection. This is done through the use of the deleteOne() or deleteMany() method.

To delete a single document, we use the deleteOne() method and pass in the query as an object. Consider the following query of the deleteOne() method which deletes the student document with the name Alice.


#Deleting data from collection
db.student.deleteOne({ name: "Alice" });

To put it differently, we have the insertMany() method to delete multiple documents at once. The following query will help us to achieve this.


delete multiple documents 
db.student.deleteMany({ age:{ $eq: 20 } })
MongoDB  Beginners Tutorial

We can see below that documents are deleted which satisfied the criteria of the insertMany() method here.

Other Examples

11. Indexing in MongoDB

In this section, we will discuss optimizing the performance of database queries of MongoDB. For this, the index technique is very important. When we create an index on a collection, MongoDB creates a data structure that stores a portion of the collection’s data in an accessible format.

The createIndex() method is used to create the index. Here, we will create an index of a collection. Below is the command to build the index. The value 1 specifies that the index should be created in ascending order. If we wanted to create the index in descending order, we would use -1 instead of 1.


#Creating index
db.student.createIndex({ name: 1 })
MongoDB  Beginners Tutorial

Now, MongoDB will automatically use it to optimize queries that match the index. Furthermore, we can get the index of the collection which we have created through the getIndexes() method. The getIndexes() method gets the list of indexes for a specific collection.

Let’s get the indexes of the student collection here which is defined.


#Getting indexes
db.student.getIndexes()

The output of the indexes in the collection student along with the information about each index, such as its name, key fields, and options.

what is mongodb

12. Retrieve Statistics of the Collection Usage in MongoDB

In addition to the above features or operations of MongoDB, we can retrieve statistics regarding the usage of a particular database or collection.

We can achieve this using the stats() method of MongoDB. The stats() method returns a document that includes statistics about the database or collection, such as its size, the number of collections or documents it contains, and the number of indexes. Below is the command of the stats() method used on the collection student.


#Usage of stats() method
db.student.stats()

The image shows the following usage statistics output of the collection student.

MongoDB  advantages

Other examples

13. Check the field existence in MongoDB

Above, we have performed various operations on the documents of the collection. Now, here we have done a checking operation on the fields of the documents. So, to check the existence of fields in a collection in MongoDB we can use the find() method with a query object that uses the $exists operator to match documents that have the specified fields. Let’s take a running command here.


#Checking existence of fields 
db.student.find({ name: { $exists: true }, age: { $exists: true } })

The aforementioned command returned the documents in the student collection below that contain both the name and email fields. Conversely, if a field does not exist in any of the documents in the collection, it will not generate results.

MongoDB  Beginners Tutorial

14. Sort the Documents of Collection in MongoDB

Significantly, MongoDB documents within a collection are not inherently sorted in any particular order. However, using the sort() technique we can order the documents in a collection.

The sort() method in MongoDb takes an object as its parameter, where the keys indicate the fields to sort by and the values indicate the sort order. Take a look at the following command where the sorting is performed in ascending order on the field age specifying the order value 1 to the sort() method.


#Usage of sort() method
db.student.find().sort({ age: 1 })

The documents are now sorted in the specified order displayed in the output.  

sort collection

Similarly, to sort by the same field age in descending order, we can use the following query but specified the order value -1.


#Sorting in descending order
db.student.find().sort({ age: -1 })

The documents of the student collection are now sorted in descending order.

More details about documents sorting can be found here.

Other examples of sorting documents

15. Search Text from the Documents Fields in MongoDB

Over and above that we have a search text feature of MongoDB to search text from the document’s fields. This feature allows us to search for text in one or more fields of a collection using a query.

Before that, we modified the collection student by inserting the new field remarks in every document to demonstrate the search text feature here. Now, the collection student looks like this.

MongoDB  Beginners Tutorial

To use text search in MongoDB, we must first create a text index on the fields we want to search using the createIndex() method. Here, we have used the field name and remarks for the text index of the collection student.


#Usage of createIndex() method
db.student.createIndex({name: "text", remarks: "text"})

Let’s now move on to search for the specific text good from the field remarks from all the documents. We have used the $text operator which is called the $search operator as an argument shown in the command.


#Usage of $text operator
db.student.find({$text: {$search: "good"}})

The documents are returned where the text good appears in the remarks field.

Other examples

16. Upsert Operation in MongoDB

In this section, we will see the upsert operation of MongoDB. The upsert operation in MongoDB is a conjunction of update and insert operations. It updates an existing document if it exists, otherwise inserts a new document. Let’s figure out with the example how the upsert feature is performed on MongoDB documents.

In general, upsert is a parameter of the update() method that takes the Boolean value that determines whether to insert a new document if no matched document exists.

Here, we have given a query where the upsert is set with the true value as the default value is false. This will update the field age where the name is Marrie, or insert a new document with this name and age if no matching document exists.


#Usage of upsert feature
db.student.updateMany(
   { name: "Marrie" },
   { $set: { age: 28 } },
   { upsert: true }
)

The document is not matched or modified because the name given is not found. Although the new document is upserted with this name and age in the collection student

MongoDB  Beginners Tutorial

We have found the document with the new value of the field name and age here.

More details about upsert feature can be found here.

17. Count Document of the Collection in MongoDB

Here, we will count the documents in the collection of MongoDB. The countDocuments() method in MongoDB is used to count the number of documents that match a given query in a collection. Also, this method returns the count of documents as an integer.

Take the following command to count the documents stored in the collection student. Note that no criteria are set inside this method so it will return the total amount of documents in the collection.


#Counting documents of collection
db.student.countDocuments()

This output indicates that there we have only 6 documents in the collection student.

learn mongodb examples

Moreover, we can use the countDocuments() method to count the number of documents that match a specific query by specifying a query document as a parameter.

Consider the following command where the countDocuments() method is provided with the condition. The condition is to match the field name where its value is Alice and count that document only.


#Usage of countDocuments() method
db.student.countDocuments({ name: "Alice" })

Furthermore, there’s only one document with the name Alice in the collection student and it is displayed in the output.

MongoDB  Beginners Tutorial

18. Fixed-Size Collection in MongoDB

In MongoDB, we can fix the size of the collection with the maximum number of documents it can store. Once this limit is reached, attempts to insert additional documents will result in an error. To create a fixed-size collection, we need to specify the maximum number of documents the collection can hold when creating the collection. This can be done using the capped option in the createCollection() method.

Consider the following command below. We have set the size option with the maximum size of 100000 in bytes that the collection can take up on disk. However, the max option sets the maximum number of documents as 100 which the collection can store.


#fixing the size of the collection
db.createCollection("student2", { capped: true, size: 1000000, max: 100 })

The new collection student2 with the fixed size is created here. Although, when we attempt to insert more documents will fail once this fixed-size limit has been met.

19. Drop Collection in MongoDB

In the last section, we are going to permanently delete a collection and all its documents from a database. Also, we already have our database and collection set up, we can move on to dropping a collection.

To drop a collection in MongoDB, we are required to use the drop() method on the collection object. Here is the command which drops the collection student from the database MyFirstDatabase.


#Usage of drop() method
db.student.drop() 

Now the student collection has been permanently deleted and all of its documents. Furthermore, use caution when using this instruction because it cannot be reversed.

MongoDB  Beginners Tutorial

20. Other Most used examples of MongoDB

21. Conclusion

In conclusion, we explore much interesting about MongoDB in this tutorial for beginners. From its installation and then the creation of the database or collection to the dropping of that collection, we have discussed it all.