Learn the basics of MongoDB by following this hands-on guide. From installation to creating databases, collections, and performing CRUD operations, this tutorial will walk you through MongoDB step-by-step.
Prerequisites for Using MongoDB
Before starting, ensure you meet these requirements to work effectively with MongoDB.
prerequisites
- Basic knowledge of object-oriented programming: Familiarity with Python, JavaScript, or similar languages is recommended.
- MongoDB Community Edition: Install the latest version from the official MongoDB website.
- MongoDB Compass GUI: A graphical interface for managing databases, collections, and queries.
Setting Up MongoDB
This section covers how to install MongoDB and its utilities.
steps
- Download the MongoDB Community Edition suitable for your operating system.
- Follow the installation instructions specific to your OS.
- Install and configure MongoDB Compass GUI. Create a desktop shortcut for ease of access.
- Optionally, install MongoDB Shell ("mongosh") for CLI-based interaction.
MongoDB CRUD Operations Basics
CRUD operations form the basis of managing data in MongoDB. Follow this workflow to explore how data creation, retrieval, updating, and deletion work.
Creating Databases and Collections
You start by creating a database and setting up collections to structure your data.
mongo
use school
db.createCollection("students")Insert Documents
Add data into your collections:
db.students.insertOne({
name: "John Doe",
age: 25,
gpa: 3.4,
courses: ["math", "science"]
});Query Documents
Retrieve data:
db.students.find({ name: "John Doe" });Update Documents
Modify existing data:
db.students.updateOne(
{ name: "John Doe" },
{ $set: { gpa: 3.8 } }
);Delete Documents
Remove unwanted data:
db.students.deleteOne({ name: "John Doe" });MongoDB Data Types
MongoDB supports a wide range of data types for flexible schema design:
- String:
{"name": "Alice"} - Number:
{"age": 30} - Boolean:
{"isAdmin": false} - Array:
{"tags": ["red", "blue"]} - Date:
{"createdAt": new Date()}
Sorting and Limiting Results
Control the order and number of results when querying MongoDB.
steps
Sort Results:
javascriptdb.students.find().sort({ gpa: -1 });This sorts students by GPA in descending order.
Limit Results:
javascriptdb.students.find().limit(3);Retrieve only three students.
Combine Sorting and Limiting:
javascriptdb.students.find().sort({ gpa: -1 }).limit(1);Retrieve the student with the highest GPA.
Indexes in MongoDB for Optimization
Indexes enhance query performance by reducing the number of scanned documents.
comparison
Without Index
db.students.find({ name: "John Doe" }).explain("executionStats");Number of scanned documents increases as the collection grows.
With Index
db.students.createIndex({ name: 1 });
db.students.find({ name: "John Doe" }).explain("executionStats");Only relevant documents are scanned.
Takeaway
MongoDB's flexible schema and NoSQL model make it an excellent choice for modern application development. This tutorial covered CRUD operations, data types, sorting, limiting, and indexing — essential tools for mastering MongoDB. Practice these concepts to build efficient and scalable databases.
FAQ
How can I connect to MongoDB from a programming language?
Most popular programming languages, such as Python, JavaScript, and Java, have dedicated libraries or drivers for MongoDB. Use official libraries like PyMongo for Python or MongoDB Node.js Driver for JavaScript.
How do I choose between embedded documents and separate collections?
Embedded documents are better for closely related data, avoiding joins. Separate collections suit data needing regular updates or sharing across different database instances.
Can MongoDB handle large volumes of data?
Yes, MongoDB is designed for scalability. You can deploy replica sets and shards for distributing data across multiple servers.
How do I recover deleted data in MongoDB?
MongoDB does not offer a built-in recovery feature for deleted documents. Consider enabling backups like MongoDB Atlas or setting up replication for data protection.
Official reference: MongoDB manual.