MongoDB Tutorial for Beginners
Entering a career in web development can be a challenge particularly traversing the huge database landscape. As a beginner, you may ask yourself which database suits contemporary app requirements, is scalable, and easy to master. MongoDB, as one of the top NoSQL databases, is built to be flexible and fast, making it a standout among novice developers.
If you’re willing to get started, download our free MongoDB course syllabus by clicking the button below to organize your learning and be job-ready!
Why MongoDB? Key Features for Beginners
MongoDB is an open-source, popular NoSQL database that stores data in extensible, JSON-like documents. It does not employ a static schema like traditional relational databases but is dynamic and unstructured. Its document-based nature has made it highly scalable and perfect for applications with evolving data needs, such as big data, web applications, and real-time analytics.
- Schema-less design: Store data in the form of JSON-like documents with changing structures.
- Horizontal scalability: Handle big datasets easily by spreading data over servers.
- High performance: Designed for high-speed read/write operations.
- Open source: No entry cost through licensing.
- Rich query language: Supports flexible and powerful queries.
Understanding MongoDB Basics
In MongoDB, data is organized into documents that resemble JSON records. Each document consists of key-value pairs, where the keys are strings and the values can take on various forms, including other documents or arrays. This adaptable schema makes it easy to create complex, hierarchical data structures.
Documents and Collections (MongoDB document, BSON, MongoDB collection)
The basic level of data in MongoDB is the document, which is a record similar to a JSON document. Documents are a collection of key-value pairs, and provide a simple but flexible hierarchical data model. The keys in a document are strings, and the values could be simple types (string, number, boolean), or complex types (embedded documents, arrays).
For example, a document of a user might look like:
{
“_id”: ObjectId(“60c72b2f9b1e8b2f9b1e8b2f”),
“name”: “Alice”,
“age”: 30,
“email”: “alice@example.com”,
“interests”: [“reading”, “hiking”],
“address”: {
“city”: “New York”,
“country”: “USA”
}
}
Behind the scenes, MongoDB documents are stored in BSON (Binary JSON). BSON is a binary encoded serialization of documents that look JSON-like. BSON is like JSON but adds additional data types like Date and ObjectID, and is designed to allow for efficient storage and traversal in the database. The ObjectId in the example above is a BSON data type.
This non-schema-based model allows developers to easily modify their data models as application requirements change.
Like a table in a relational database, a collection is a set of documents. However, a collection does not strict schema implementation like a relational table has. Documents in the same collection can have different fields and structures, giving flexibility.
For example, in a collection of “users”, we can have documents with different fields:
{
“name”: “Bob”,
“age”: 25
}
This schema-less nature allows developers to adapt their data models easily as application requirements evolve.
JSON and BSON
JSON, or JavaScript Object Notation, is a lightweight and easy-to-read text format for data. It’s an open standard that’s become a go-to for data interchange, especially in web APIs, thanks to its straightforward nature and ability to work across different programming languages. JSON can handle basic data types like strings, numbers, booleans, arrays, and objects.
Here’s a simple example of a JSON object:
{
“name”: “Jane Doe”,
“age”: 28,
“isStudent”: true,
“courses”: [“History”, “Math”]
}
On the other hand, BSON, which stands for Binary JSON, is a binary-encoded format designed for JSON-like documents. It was created specifically for MongoDB to overcome some of JSON’s limitations. While BSON isn’t human-readable like JSON, it offers better efficiency for storage and database traversal.
Key Differences Between JSON and BSON
- Format: JSON is text-based, whereas BSON is binary.
- Data Types: BSON goes beyond JSON by supporting extra data types that JSON doesn’t natively include, such as Date, ObjectId, and BinData (which is used for binary data like images). In JSON, dates are usually stored as strings, which means they need extra parsing.
- Performance: BSON is quicker to parse and decode than JSON because it carries length information for each key-value pair, allowing databases to skip over unnecessary fields more efficiently.
- Size: BSON can sometimes take up more space than JSON for smaller documents due to the added metadata (like type and length info), but for larger or more complex documents that include binary data, BSON can actually be more space-efficient.
In summary, while JSON is perfect for exchanging data between different systems, BSON is tailored for the internal workings of a database like MongoDB.
Suggested: MongoDB Online Course.
MongoDB Architecture
The MongoDB design is centered around the mongod process, which is the main server that handles all data requests. The users communicate with the server using a number of client applications, including the mongo shell.
Following is a diagram illustrating the key components:
- MongoDB Server (mongod): It is the primary background daemon process on the server computer. It oversees all the data, serves client connections, runs queries, and performs other database operations. It listens to client application requests.
- mongo shell: It is an interactive JavaScript command-line shell. It is a client tool that enables developers and administrators to connect to a mongod instance, run JavaScript commands, interact with databases, and query collections.
- Client Applications: In deployment, applications (e.g., a web server hosting a Node.js or Python application) talk to the mongod process to read and write data, instead of invoking the mongo shell directly.
Explore: Full Stack Developer Salary for Freshers.
Installing MongoDB: Setting Up Your First Database
Here are the steps to install and configure your MongoDB database:
Installation (Windows/Mac/Linux)
- Download from the official MongoDB website
- Install and proceed with the platform-specific instructions.
- Launch MongoDB using the mongod command in your terminal.
# For Linux/Mac
mongod –dbpath /path/to/data/directory
# For Windows (in Command Prompt)
mongod –dbpath C:\data\db
It is simple to install MongoDB, but it is slightly different depending on your operating system. There is a free version called MongoDB Community Edition which you can use for testing and development.
Step 1: Download the Installer:
Download the MongoDB Community Server from the official MongoDB site. You will be prompted to select operating system (Windows, macOS, or Linux), version, and package type (i.e., .msi for Windows, .tgz for Linux).
Step 2. Install MongoDB:
- On Windows: The .msi installer has a simple setup wizard. During installation, you can install both server and management tools with a “Complete” installation. Installation as a service is typically advised so that MongoDB starts automatically when your system boots up.
- On macOS: Where it is possible, the recommended practice is to install using a package manager like Homebrew. Something like brew tap mongodb/brew followed by brew install mongodb-community can do the job.
- On Linux (e.g., Ubuntu): You typically install MongoDB using your system package manager after you have added the official MongoDB repository. This involves a few commands to import the GPG key, create a list file for the repository, then run sudo apt-get install -y mongodb-org.
Step 3: Start the MongoDB Server (mongod):
After installation, you would need to start the MongoDB server. With Windows, it will automatically start if you installed it as a service. Otherwise, you would run the mongod command in your command prompt.
With Linux, you would run sudo systemctl start mongod. You may also need to create a data directory (/data/db by default) where MongoDB will store its files.
Step 4: Install the MongoDB Shell (mongosh):
The new MongoDB Shell (mongosh) is a fully functional command-line client that is not typically included in the base server installer and will need to be downloaded and installed separately. It’s the primary means of manipulating your MongoDB database from the command line.
Step 5: Connect and Test:
Once the mongod server is running, you can open a new terminal window and connect to it using the MongoDB Shell via the mongosh command. You can then type commands like show dbs to verify that your installation is successful.
Connecting to MongoDB (MongoDB connection, mongo client)
To connect to a MongoDB database, a client application needs to connect to the mongod running as the MongoDB server. The usual way to establish a connection to the MongoDB server is by using a MongoDB connection URI.
This URI defines the connection details such as the protocol, host, port, and connection credentials to use if there are any.
For example, a simple URI might look like this: mongodb://:.
Thus, if you are connecting to a local server running on the default port, the connection URI would be mongodb://localhost:27017.
Many client drivers for different programming languages (e.g., Python, Node.js, Java) will use the URI to establishing the connection, authenticating, and sending and receiving data to/from the MongoDB Server. It is the same for the mongosh command line tool, which also uses a connection string format.
Related: Angular JS Course Tutorial for Beginners.
CRUD Operations in MongoDB
CRUD stands for Create, Read, Update, and Delete – the four basic operations for interacting with a database. MongoDB provides very powerful and flexible operations for each of these on the documents inside collections.
We will use the mongosh (MongoDB Shell) for the code examples. We will assume that we are connected to a database called mydb and we are working with a collection called products.
Create Operations (Insert Documents)
The first thing you need to know is how to add a new document into a collection. You will use the insertOne() and insertMany() methods.
db.collection.insertOne(document): This method will insert a single document into a collection.
db.products.insertOne({
name: “Laptop Pro”,
brand: “TechCorp”,
price: 1200,
stock: 50,
features: [“16GB RAM”, “512GB SSD”, “Full HD Display”]
});
db.collection.insertMany([document1, document2, …]): Insert multiple documents into a collection.
db.products.insertMany([
{
name: “Wireless Mouse”,
brand: “ErgoGear”,
price: 25,
stock: 200
},
{
name: “Mechanical Keyboard”,
brand: “KeyMaster”,
price: 90,
stock: 100,
color: “Black”
},
{
name: “USB-C Hub”,
brand: “ConnectAll”,
price: 45,
stock: 150,
ports: [“HDMI”, “USB-A”, “Ethernet”]
}
]);
Read Operations (Query Documents)
The find() method is used to retrieve documents from a collection and it returns a cursor to the documents that match the query.
db.collection.find(query): This method finds documents that satisfy the query criteria. An empty query {} will return all documents.
// Find all products
db.products.find({});
// Find products with price greater than 50
db.products.find({ price: { $gt: 50 } });
// Find products with brand “TechCorp” and stock less than 100
db.products.find({ brand: “TechCorp”, stock: { $lt: 100 } });
// Find products with “reading” in the interests array (for user collection example)
db.users.find({ interests: “reading” });
db.collection.findOne(query): This method returns a single document that satisfies the query criteria.
// Find one product with the name “Laptop Pro”
db.products.findOne({ name: “Laptop Pro” });
Projection: A projection document can specify which fields (1 for include, 0 for exclude) to return.
// Find products, only return name and price
db.products.find({}, { name: 1, price: 1, _id: 0 }); // _id is included by default, exclude explicitly
Update Operations (Modify Documents)
The updateOne(), updateMany(), and replaceOne() methods are used to make changes to existing documents.
db.collection.updateOne(filter, update, options): It is used to update a single document that matches the filter.
// Increase stock of “Laptop Pro” by 10
db.products.updateOne(
{ name: “Laptop Pro” },
{ $inc: { stock: 10 } }
);
// Set the color of “Wireless Mouse” to “Grey”
db.products.updateOne(
{ name: “Wireless Mouse” },
{ $set: { color: “Grey” } }
);
db.collection.updateMany(filter, update, options): Updates all documents that match the filter.
// Decrease stock of all products by 5
db.products.updateMany(
{},
{ $inc: { stock: -5 } }
);
// Add a “last_updated” field to all documents that don’t have it
db.products.updateMany(
{ last_updated: { $exists: false } },
{ $currentDate: { last_updated: true } }
);
db.collection.replaceOne(filter, replacement_document): Completely replaces a single document for a new document.
// Replace the “Wireless Mouse” document with a new one
db.products.replaceOne(
{ name: “Wireless Mouse” },
{
product_name: “ErgoGear Silent Mouse”,
category: “Peripherals”,
price: 30,
available: true
}
);
Delete Operations (Remove Documents)
The deleteOne() and deleteMany() methods are used to remove documents from a collection.
db.collection.deleteOne(filter): It deletes a single document that matches the filter.
// Delete the “USB-C Hub” product
db.products.deleteOne({ name: “USB-C Hub” });
db.collection.deleteMany(filter): It deletes all documents that match the filter. All documents in the collection are deleted when the filter is empty {}.
// Delete all products with stock less than 10
db.products.deleteMany({ stock: { $lt: 10 } });
// Delete all documents from the collection (use with caution!)
// db.products.deleteMany({});
Suggested: MERN Stack Online Course.
Working with MongoDB Shell
The MongoDB Shell (mongosh) provides a versatile command-line interface for interacting with your MongoDB deployments. You can run administrative commands, run query commands, and develop applications directly from the shell.
Connection to MongoDB:
You can connect to a running mongod by simply typing mongosh in your terminal. By default, it assumes you want to connect to a MongoDB server running on localhost on port 27017.
mongosh
If your server is running elsewhere, use a different connection string:
mongosh “mongodb://myhost.example.com:27017/mydatabase”
Basic Operations:
Once you connect, you will see a prompt that looks like test> (or whatever database you connected to).
Show Databases:
To see the databases available:
show dbs
Switch Databases:
To switch to an existing database or to create a new one:
use myappdb // Switches to ‘myappdb’, creates it if it doesn’t exist
Show Collections:
To show collections in the current database:
show collections
Insert a Document:
To insert a document into a collection (e.g., users):
db.users.insertOne({ name: “Alice”, age: 30 });
Find Documents:
To find documents in a collection:
db.users.find({}); // Find all users
db.users.find({ age: { $gt: 25 } }); // Find users older than 25
Update a Document:
To update an existing document:
db.users.updateOne({ name: “Alice” }, { $set: { age: 31 } });
Delete a Document:
To delete a document:
db.users.deleteOne({ name: “Alice” });
Exiting the Shell:
To exit the mongosh, either invoke the exit command or press Ctrl+C twice.
mongosh has a variety of commands and JavaScript capabilities, making it an invaluable tool to use when developing and administering a MongoDB deployment.
Recommended: MEAN Stack Online Course
Indexing in MongoDB
Indexes within MongoDB are a type of data structure that hold a small amount of data from the collection into an easily traversable schema. Indexes greatly enhance queries by minimizing the amount of data written to disk and the amount of data scanned.
Without indexes, MongoDB is required to execute full collection scans (scanning every document in a collection) to select those documents that match the query statement. This can take a long time if you are querying a large collection.
How Indexes Work:
Indexes can be thought of as the index of a book. When you want to read a topic or a section in a book, you can look it up in the index and find the corresponding page number you need to flip to. You won’t have to flip through the book back to front before reading your topic.
Similarly, a MongoDB index allows the database to only locate documents that contain specific field values rather than scanning each document in the collection.
Types of Indexes:
- Single Field Index: It is an index on a single field in a document.
db.products.createIndex({ “item”: 1 }); // Ascending order
- Compound Index: An index on multiple fields and is sensitive to the ordering of fields in a compound index.
db.users.createIndex({ “username”: 1, “age”: -1 }); // username ascending, age descending
- Multikey Index: Used to index fields that have arrays.
db.products.createIndex({ “tags”: 1 });
- Text Index: Supports text search on string content.
db.articles.createIndex({ “content”: “text” });
Creating an Index:
To create an index you will use the createIndex method to create each index.
// Create a single field index on the ’email’ field in the ‘users’ collection
db.users.createIndex({ “email”: 1 });
// Create a compound index on ‘orderId’ and ‘itemId’ in the ‘orders’ collection
db.orders.createIndex({ “orderId”: 1, “itemId”: 1 });
Advantages of Indexing:
- Faster Query Performance: Indexes greatly increase the performance of read operations.
- Better Sort Performance: Indexing greatly increases the performance of sorting operations if the sort key is indexed.
Disadvantages of Indexing:
- Indexes consume disk space.
- Indexes add overhead to write operations (insert, update, delete) since the index must also be updated.
- Good indexing is about understanding your common query patterns.
Upgrade: Full Stack Course Online.
Data Modeling in MongoDB
Data modeling in MongoDB is a significant step in creating your documents and how to relate them to each other. Because MongoDB does not require fixed schemas like relational databases, it allows for two primary approaches to data modeling, embedding and referencing.
Embedding (Denormalization): This is the storing of related information within a single document.
- Embedding is best for one-to-one or one-to-many relationships where the associated information is largely read at the same time.
- Embedding will allow better read performance as one query retrieves all the necessary information rather than having to perform JOIN operations.
For example: Storing customer address an adjacent details in the customer document.
// In the customers collection
{
_id: “customer_id_1”,
name: “John Doe”,
orders: [“order_id_1”, “order_id_2”]
}
// In the orders collection
{
_id: “order_id_1”,
customer_id: “customer_id_1”,
items: [“item_id_a”, “item_id_b”],
date: “2025-07-28”
}
Referencing (Normalization): This uses references to store relationships between documents (typically the _id of the associated document).
- This is appropriate for many-to-many relationships or when the data being related is large and not always required with the primary document.
- This is helpful because it limits data duplication and reduces the odds that your documents get too large.
Example: Storing references to order documents in a customer document.
// In the customers collection
{
_id: “customer_id_1”,
name: “John Doe”,
orders: [“order_id_1”, “order_id_2”]
}
// In the orders collection
{
_id: “order_id_1”,
customer_id: “customer_id_1”,
items: [“item_id_a”, “item_id_b”],
date: “2025-07-28”
}
Which option you utilize, embedding or referencing, is entirely dependent on your application’s use case, data size, and relationship types. The best schemas use some combination of the two options.
Explore related courses: AII IT training courses.
Conclusion
We hope this MongoDB database tutorial helps you understand the fundamentals. MongoDB is a NoSQL database that is flexible, scalable, and high-performing. You have learned CRUD functionality, indexing, and a powerful shell now. MongoDB is a comprehensive platform for dealing with the kind of dynamic data we see in many applications today. To learn more about MongoDB concepts and build dynamic applications, take a look at our MongoDB Course in Chennai!