Your First MongoDB Lab

MongoDBMongoDBBeginner
Practice Now

Introduction

Welcome to LabEx! This is your first MongoDB lab. Don't worry if you've never used a database before - we'll guide you through every step.

First, let's understand what MongoDB is: MongoDB is a database system that stores data in a flexible, document format. Unlike traditional spreadsheets, MongoDB allows you to organize data in a more natural way, similar to how you might organize files in folders on your computer.

In this lab, you'll learn how to:

  1. Start the MongoDB shell and understand what it is
  2. Create your first database and collection
  3. Add and view data in MongoDB
  4. Count and remove data

These skills will form the foundation of your MongoDB journey. Let's get started!

Click the Continue button below to begin the lab.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb/BasicOperationsGroup -.-> mongodb/start_mongodb_shell("`Start MongoDB Shell`") mongodb/BasicOperationsGroup -.-> mongodb/create_database_collection("`Create Database and Collection`") mongodb/BasicOperationsGroup -.-> mongodb/insert_document("`Insert Document`") mongodb/BasicOperationsGroup -.-> mongodb/bulk_insert_documents("`Bulk Insert Documents`") mongodb/BasicOperationsGroup -.-> mongodb/delete_document("`Delete Document`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") subgraph Lab Skills mongodb/start_mongodb_shell -.-> lab-420660{{"`Your First MongoDB Lab`"}} mongodb/create_database_collection -.-> lab-420660{{"`Your First MongoDB Lab`"}} mongodb/insert_document -.-> lab-420660{{"`Your First MongoDB Lab`"}} mongodb/bulk_insert_documents -.-> lab-420660{{"`Your First MongoDB Lab`"}} mongodb/delete_document -.-> lab-420660{{"`Your First MongoDB Lab`"}} mongodb/find_documents -.-> lab-420660{{"`Your First MongoDB Lab`"}} mongodb/query_with_conditions -.-> lab-420660{{"`Your First MongoDB Lab`"}} end

Start MongoDB Shell

Before we start MongoDB, we first need to open a terminal in your LabEx VM. You have two ways to do this:

  1. Desktop Interface: Look at the left side of your desktop and click the icon labeled Xfce Terminal.
  2. Terminal Interface: Click the tab at the top of your LabEx VM window labeled Terminal Interface.
open the terminal

Both methods work equally well - they're just different ways to access the same lab environment. Choose whichever you prefer!

Now, let's start the MongoDB shell, which is like a control panel for our database. Think of the shell as a way to talk directly to MongoDB - you type commands, and MongoDB responds.

To start the MongoDB shell, type this command and press Enter:

mongosh

You should see something like this:

Current Mongosh Log ID: 65a7f3e5f1a1234567890abc
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+x.y.z
Using MongoDB:          x.y.z
Using Mongosh:          x.y.z
alt text

This means you're now connected to MongoDB! The connection message shows that MongoDB is running on your computer (that's what '127.0.0.1' means - it's your computer's address to itself).

Let's try our first MongoDB command to see what databases exist. Type:

show dbs

Make sure to type the command in the mongosh shell, not in your terminal.

You should see a list of databases, similar to this:

admin             40.00 KiB
config            12.00 KiB
local             40.00 KiB

These are default databases that MongoDB creates automatically. Don't worry about them for now - we'll create our own database in the next step.

Create Your First Database

In MongoDB, data is organized in databases. A database is like a container that holds collections of related information. Think of it like a filing cabinet where you store different types of documents.

To create a new database (or switch to it if it already exists), type:

use mylab_database

You should see:

switched to db mylab_database

Now, let's add some data. In MongoDB, data is stored in "collections" (similar to folders) and "documents" (similar to files). A document is a piece of data that contains fields and values, like a person's name and age.

Let's create our first collection called "users" and add a document to it:

db.users.insertOne({ name: "John Doe", age: 30 })

Let's break down this command:

  • db refers to our current database (mylab_database)
  • users is the name of our collection, which will be created automatically
  • insertOne is the command to add one document
  • The curly braces { } contain our document data with two fields: name and age

You should see something like:

{
  acknowledged: true,
  insertedId: ObjectId("65b2f3...")
}

MongoDB automatically creates a unique ID (ObjectId) for each document, so we can find it later.

To see what we just added, type:

db.users.find()

You should see:

[
  {
    _id: ObjectId("65b2f3..."),
    name: 'John Doe',
    age: 30
  }
]

Add More Data

Now that we understand how to add one document, let's create another collection and add multiple documents at once. This time, we'll store information about books.

First, let's add one book:

db.books.insertOne({
    title: "MongoDB Basics",
    author: "Jane Smith",
    year: 2023
})

MongoDB will automatically create the 'books' collection when we add our first book.

Now let's try something more powerful - adding multiple documents at once using insertMany. This is useful when you have lots of data to add:

db.books.insertMany([
    {
        title: "Python Programming",
        author: "John Doe",
        year: 2022
    },
    {
        title: "Data Science Handbook",
        author: "Alice Johnson",
        year: 2021
    }
])

Notice the square brackets [ ] - they tell MongoDB we're inserting multiple documents at once.

You should see something like:

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("65b2f4..."),
    '1': ObjectId("65b2f5...")
  }
}

Let's see all our books:

db.books.find()

View and Count Data

Now that we have some data in our database, let's learn different ways to view and count it. MongoDB provides several methods to find exactly the information you want.

To count how many books we have, type:

db.books.countDocuments()

This command counts all documents in the books collection. You should see:

3

To find specific books, we can use the find() command with a "query". A query is like a filter that tells MongoDB what we're looking for.

To find books by a specific author, type:

db.books.find({ author: "John Doe" })

The part inside the curly braces { author: "John Doe" } is our filter - it tells MongoDB to only show books where the author is "John Doe".

You should see:

[
  {
    _id: ObjectId("65b2f4..."),
    title: 'Python Programming',
    author: 'John Doe',
    year: 2022
  }
]

Let's try another query to find books published in 2023:

db.books.find({ year: 2023 })

Remove Data

Finally, let's learn how to remove data from our database. Just like we can add one or many documents, we can also remove them in the same way.

To remove one specific book, use deleteOne:

db.books.deleteOne({ title: "MongoDB Basics" })

The part in curly braces tells MongoDB which book to delete. You should see:

{ acknowledged: true, deletedCount: 1 }

To remove multiple documents at once based on a condition, use deleteMany. Let's remove all books published before 2022:

db.books.deleteMany({ year: { $lt: 2022 } })

Here, $lt means "less than" - so we're deleting all books where the year is less than 2022.

To check what's left in our collection, type:

db.books.find()

When you're done exploring, you can exit the MongoDB shell by typing:

exit

Summary

Congratulations! You've completed your first MongoDB lab and taken your first steps into the world of databases. Let's recap what you've learned:

  1. How to start and use the MongoDB shell
  2. How databases and collections organize your data
  3. How to add single and multiple documents
  4. How to find specific information using queries
  5. How to remove data you no longer need

These might seem like small steps, but they're the foundation of working with MongoDB. Every database expert started exactly where you are now!

Remember, learning databases is a journey, and you've just taken your first steps. Keep practicing, stay curious, and don't be afraid to experiment. Your next lab is just a click away!

Other MongoDB Tutorials you may like