- Published on
MongoDB for Beginners: A Complete Guide
- Authors
- Name
- Diego Herrera Redondo
- @diegxherrera
MongoDB is a popular NoSQL database known for its flexibility, scalability, and ease of use with modern applications. Unlike traditional relational databases that store data in tables with rows and columns, MongoDB stores data in a more flexible, document-based format using JSON-like objects called documents. This approach makes it ideal for managing unstructured or semi-structured data and allows for faster development with dynamic schemas.
In this guide, we’ll explore the basics of MongoDB, explain how it works, and provide practical examples to get you started.
What is MongoDB?
MongoDB is a NoSQL database, meaning it doesn’t use tables, rows, or columns. Instead, MongoDB organizes data in documents and collections:
- Document: A JSON-like object that represents a single data record, with key-value pairs. Documents in MongoDB are stored in Binary JSON (BSON) format.
- Collection: A group of documents, similar to a table in relational databases. Collections store documents that usually share the same structure but allow for flexibility in schema.
MongoDB is designed to handle large amounts of data with ease and supports horizontal scaling, making it an excellent choice for high-traffic applications or projects that need to handle complex and evolving data.
Setting Up MongoDB
To start working with MongoDB, you’ll need to install it. MongoDB provides installers for various platforms (Windows, macOS, and Linux). You can download MongoDB Community Edition for free from MongoDB’s official website.
After installation, you can interact with MongoDB through:
- MongoDB Shell: A command-line interface for MongoDB.
- MongoDB Compass: A GUI that makes it easy to visualize, manipulate, and analyze data in MongoDB.
- MongoDB Drivers: Drivers for various programming languages (e.g., Node.js, Python) to integrate MongoDB with your applications.
In this guide, we’ll primarily focus on using MongoDB Shell for simplicity.
MongoDB Basics
Connecting to MongoDB
Once MongoDB is running, open your terminal or command prompt and enter the MongoDB shell by typing:
mongosh
This command connects you to the MongoDB server, allowing you to start interacting with your database.
Creating a Database
In MongoDB, databases are created automatically when you first insert data into them. To switch to a database (and create it if it doesn’t exist), use the use command:
use myDatabase
This command switches to myDatabase or creates it if it doesn’t exist. Note that databases in MongoDB don’t physically exist until they contain at least one collection with data.
Creating a Collection
To create a collection, simply insert a document into it. Let’s create a collection called users by inserting a document:
db.users.insertOne({
name: "John Doe",
age: 30,
email: "john.doe@example.com"
});
This command creates the users collection and inserts a document with the specified fields.
CRUD Operations in MongoDB
CRUD stands for Create, Read, Update, and Delete—the four basic operations for managing data. Let’s go through each operation with examples.
- Create: Inserting Data
In MongoDB, you can insert data into a collection using insertOne for a single document or insertMany for multiple documents.
Inserting a Single Document
db.users.insertOne({
name: "Jane Smith",
age: 28,
email: "jane.smith@example.com"
});
This command adds a new user document to the users collection.
Inserting Multiple Documents
db.users.insertMany([
{ name: "Alice Johnson", age: 35, email: "alice.johnson@example.com" },
{ name: "Bob Brown", age: 22, email: "bob.brown@example.com" }
]);
This command inserts multiple documents into the users
collection in a single operation.
- Read: Querying Data
To retrieve data from a MongoDB collection, use the find method. By default, find returns all documents in a collection.
Retrieve All Documents
db.users.find();
This command returns all documents in the users
collection.
Retrieve Documents with a Filter
To filter documents, pass a query object to find. For example, to find users over the age of 25:
db.users.find({ age: { $gt: 25 } });
The lt (less than), lte (less than or equal to), and $eq (equal to), for creating complex queries.
Retrieve a Single Document
To retrieve a single document, use findOne:
db.users.findOne({ name: "John Doe" });
This command finds the first document where the name field matches “John Doe.”
- Update: Modifying Data
To update data, use the updateOne or updateMany methods. These methods allow you to modify specific fields in existing documents.
Updating a Single Document
db.users.updateOne(
{ name: "John Doe" },
{ $set: { age: 31 } }
);
This command updates the age of the user with the name “John Doe” to 31. The $set operator specifies the fields to be updated.
Updating Multiple Documents
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
);
This command updates all documents where age is less than 30, adding a new field called status with the value “young.”
- Delete: Removing Data
To delete data, use deleteOne or deleteMany.
Deleting a Single Document
db.users.deleteOne({ name: "Bob Brown" });
This command deletes the document where the name field matches “Bob Brown.”
Deleting Multiple Documents
db.users.deleteMany({ age: { $gt: 30 } });
This command deletes all documents where age is greater than 30.
Working with Embedded Documents and Arrays
MongoDB supports embedded documents and arrays, allowing you to store related data within a single document. This feature is especially useful when working with complex, hierarchical data structures.
Example of an Embedded Document
Suppose you want to store an address within the users document:
db.users.insertOne({
name: "Charlie Green",
age: 27,
email: "charlie.green@example.com",
address: {
street: "123 Main St",
city: "Somewhere",
state: "CA",
zip: "90210"
}
});
The address field is an embedded document with its own key-value pairs.
Example of an Array
MongoDB allows you to store arrays in documents, which is useful for lists. Here’s an example:
db.users.insertOne({
name: "Diana Prince",
age: 32,
email: "diana.prince@example.com",
hobbies: ["reading", "traveling", "sports"]
});
In this case, the hobbies
field is an array containing multiple values.
Querying Embedded Documents and Arrays
You can query embedded documents and arrays using dot notation. For example, to find users in the city of “Somewhere”:
db.users.find({ "address.city": "Somewhere" });
To find users with “reading” as one of their hobbies:
db.users.find({ hobbies: "reading" });
This command returns any document where “reading” is one of the values in the hobbies array.
Additional MongoDB Commands
Counting Documents
To count the number of documents in a collection, use countDocuments:
db.users.countDocuments({ age: { $gt: 25 } });
This command counts the users who are older than 25.
Sorting Results
To sort query results, use sort:
db.users.find().sort({ age: -1 });
This command sorts the users by age in descending order (use 1 for ascending).
Limiting Results
To limit the number of results returned, use limit:
db.users.find().limit(5);
This command retrieves only the first five documents in the users collection.