Developer Guides

MongoDB Tutorial for Beginners: CRUD Queries Explained

Learn MongoDB step-by-step, from installation to CRUD operations, in this beginner's guide.

3 min read

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

  1. Download the MongoDB Community Edition suitable for your operating system.
  2. Follow the installation instructions specific to your OS.
  3. Install and configure MongoDB Compass GUI. Create a desktop shortcut for ease of access.
  4. 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.

bash
mongo
use school
db.createCollection("students")

Insert Documents

Add data into your collections:

javascript
db.students.insertOne({
  name: "John Doe",
  age: 25,
  gpa: 3.4,
  courses: ["math", "science"]
});

Query Documents

Retrieve data:

javascript
db.students.find({ name: "John Doe" });

Update Documents

Modify existing data:

javascript
db.students.updateOne(
  { name: "John Doe" },
  { $set: { gpa: 3.8 } }
);

Delete Documents

Remove unwanted data:

javascript
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

  1. Sort Results:

    javascript
    db.students.find().sort({ gpa: -1 });

    This sorts students by GPA in descending order.

  2. Limit Results:

    javascript
    db.students.find().limit(3);

    Retrieve only three students.

  3. Combine Sorting and Limiting:

    javascript
    db.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

javascript
db.students.find({ name: "John Doe" }).explain("executionStats");

Number of scanned documents increases as the collection grows.

With Index

javascript
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.