MongoDB beginner guide

MongoDB beginner guide

Learn the basics of MongoDB by creating your first database.

·

8 min read

Introduction

Starting to explore databases may feel overwhelming, but don't worry! I'm here to guide you through the captivating world of MongoDB, a robust and versatile NoSQL database tailored for modern applications. In this beginner-oriented introduction, we'll unravel the intricacies of MongoDB and discover how it can enhance your development journey. So, let's dive in and unleash the potential of MongoDB!

💡 Checkout the MongoDB cheat sheet to find all of the most commonly used commands organized in tables with some quick explanations, ideal for a quick reference.

SQL vs. NoSQL: A tale of two database paradigms

When it comes to choosing between SQL and NoSQL databases, it's important to understand their key differences.

SQL databases, also known as relational databases, rely on structured data and predefined schemas, making them well-suited for applications with strict data requirements. They use the SQL language for data manipulation and are ideal for handling complex queries and transactions. On the flip side, NoSQL databases, like MongoDB, are designed for unstructured data, offering the flexibility and scalability that modern applications demand. They're schema-less, utilize various data models (such as document, key-value, or graph), and are well-suited for handling large volumes of diverse data. In a nutshell, SQL databases excel in environments with well-defined data structures, while NoSQL databases shine in dynamic, ever-evolving landscapes.

MongoDB: Simplify your database

As developers, we're on a perpetual quest for tools that simplify our lives, and MongoDB fits the bill! Being a NoSQL database, it's engineered to manage unstructured data - a prevalent characteristic of contemporary applications. MongoDB's document-oriented and schema-less design delivers the adaptability and scalability developers crave.

Why MongoDB? Unveiling the core advantages

  1. Adaptable data model: Say goodbye to inflexible tables and rows; MongoDB stores data in a dynamic, JSON-like format called BSON, enabling easy adaptation to evolving requirements and assorted data types.

  2. Scalability: MongoDB is crafted for horizontal scaling, letting you disseminate your data across numerous servers for amplified performance and high availability.

  3. Sophisticated query language: MongoDB takes pride in its potent query language that facilitates complex data manipulation, making operations like filtering, sorting, and updating data a breeze.

  4. Thriving ecosystem: With an extensive community and a plethora of tools and integrations, MongoDB furnishes the resources and support you need for an impeccable development experience.

MongoDB structure

Now we'll go over the structure of MongoDB so that you can understand how a database can look. Its key components include databases, collections, and documents.

  1. Databases: MongoDB organizes data into databases, which serve as containers for related collections. A database can hold multiple collections and provides logical separation of data.

  2. Collections: Collections in MongoDB are groups of related documents. They are analogous to tables in relational databases. Collections do not enforce a fixed schema, allowing documents within the same collection to have varying structures.

  3. Documents: Documents are the fundamental unit of data in MongoDB. They are stored in BSON format (Binary JSON), which allows for efficient storage and retrieval. Documents are similar to JSON objects and can contain nested fields and arrays. They provide a flexible schema, enabling developers to easily adapt to changing data requirements.

  4. Fields: Documents consist of fields, which are key-value pairs. Fields can store various types of data, such as strings, numbers, arrays, and nested documents. Unlike traditional databases, MongoDB allows each document within a collection to have different fields, providing the flexibility to store heterogeneous data.

  5. Indexes: MongoDB supports indexing on fields within a collection. Indexes improve query performance by enabling fast data retrieval based on specified fields. By creating appropriate indexes, developers can efficiently search, sort, and filter data.

  6. Query Language: MongoDB Query Language (MQL) is used to interact with the database and perform various operations, such as reading, writing, updating, and deleting documents. MQL provides a rich set of operators and expressions to construct complex queries.

Overall, MongoDB's structure provides developers with the flexibility to adapt to evolving data models and handle diverse data requirements. It enables efficient storage, retrieval, and querying of documents in a scalable and distributed manner.

Launching your MongoDB adventure

The best way to get started with MongoDB is by creating local databases in interact with them using the MongoDB Shell; the following paragraph will guide you through the installation.

Introducing the MongoDB Shell: mongosh

The MongoDB Shell, known as mongosh, serves as a fully functional JavaScript and Node.js 16.x REPL environment, allowing seamless interaction with MongoDB deployments. It's an excellent tool for testing and learning.

The following instructions will redirect you to the MongoDB docs so that we know the process is always up to date.

Downloading and installing mongosh

For guidance on downloading and installing mongosh, refer to Install mongosh.

Connecting to a MongoDB deployment

Once you've installed the MongoDB Shell and added it to your system PATH, connecting to a MongoDB deployment is quick; in the following sections, we'll explore how to start a local database and how to connect to it. For more information, check out Connect to a Deployment.

Connecting to a MongoDB instance: Your gateway to the database world

Establishing a connection to a MongoDB instance is the crucial first step in harnessing the power of your database. With the MongoDB Shell installed and configured, you're all set to interact with your MongoDB deployment.

Simply run the mongosh command followed by the connection string, which includes your MongoDB instance's host, port, and authentication details. Voilà! You're now connected and can explore, manipulate, and manage your data using the rich array of MongoDB Shell commands.

In this example, we’ll use a local instance to practice, so run the following command:

mongosh "mongodb://localhost:27017"

This will establish a connection to your local instance of the database. If the local instance is not running, you can follow the steps here:

  1. Open a terminal (Command Prompt on Windows or Terminal on macOS/Linux).

  2. Run the following command to start the MongoDB server with default settings:

For Windows:

mongod

For macOS (using Homebrew):

brew services start mongodb-community

For Linux (using the MongoDB package):

sudo systemctl start mongod

After running the appropriate command, the MongoDB server should start, and you should see an output indicating it's running.

Working with Databases: A general introduction to using MongoDB

This section provides a step-by-step guide on how to create and interact with a basic database. Following these steps will not only help you get started but also boost your confidence in managing databases.

💡 In this example, we’ll create a basic library database and interact with a "books" collection.

Make sure your local database instance is running!

Step 1: Create or switch to a database

To create a new database or switch to an existing one, run the use <databaseName> command in the MongoDB Shell. If the database doesn't exist, MongoDB will create it automatically once you insert data.

use LibraryDB

The console will return a response similar to the following:

$ use LibraryDB
switched to db LibraryDB
LibraryDB>

Step 2: List available databases

View all databases in your MongoDB instance by executing the show dbs command. Note that only databases containing data will be displayed.

show dbs

The console will list the available databases; note that the database we just created doesn’t show up yet as we did not create any collection or add any data to it.

admin        40.00 KiB
config       60.00 KiB
local        72.00 KiB

Step 3: Create a collection

Create a new collection in your database using the db.createCollection("<collectionName>") command. A collection is a container for your data, similar to a table in SQL databases.

db.createCollection("books")

The console will display a successful response:

LibraryDB> db.createCollection("books")
{ ok: 1 }

Step 4: Insert data

Insert documents (data records) into your collection using the following commands:

  • For a single document: db.<collectionName>.insertOne(<document>)

  • For multiple documents: db.<collectionName>.insertMany(<arrayOfDocuments>)

db.books.insertOne({title: "Moby Dick", author: "Herman Melville", year: 1851})

The console will return a response including the id of the object we just pushed to the database:

LibraryDB> db.books.insertOne({title: "Moby Dick", author: "Herman Melville", year: 1851})
{
  acknowledged: true,
  insertedId: ObjectId("644e6fef4fa7719a3f760b0b")
}

Step 5: Query data

Retrieve data from your collection with the db.<collectionName>.find(<query>, <projection>) command. Use query filters and projections to refine your results or adjust the returned fields.

db.books.find({author: "Herman Melville"})

This command will return the object associated with our search:

LibraryDB> db.books.find({author: "Herman Melville"})
[
  {
    _id: ObjectId("644e6fef4fa7719a3f760b0b"),
    title: 'Moby Dick',
    author: 'Herman Melville',
    year: 1851
  }
]

Step 6: Update data

Modify existing documents in your collection using these commands:

  • For a single document: db.<collectionName>.updateOne(<filter>, <update>)

  • For multiple documents: db.<collectionName>.updateMany(<filter>, <update>)

  • To replace a single document: db.<collectionName>.replaceOne(<filter>, <replacement>)

db.books.updateOne({title: "Moby Dick"}, {$set: {year: 1852}})

This will edit the selected field in the object:

LibraryDB> db.books.updateOne({title: "Moby Dick"}, {$set: {year: 1852}})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Step 7: Delete data

Remove documents from your collection with these commands:

  • For a single document: db.<collectionName>.deleteOne(<filter>)

  • For multiple documents: db.<collectionName>.deleteMany(<filter>)

db.books.deleteOne({title: "Moby Dick"})

The console will return a message letting you know that the object has been deleted:

LibraryDB> db.books.deleteOne({title: "Moby Dick"})
{ acknowledged: true, deletedCount: 1 }

Step 8: Drop a database

To delete an entire database, first, switch to the target database using the use <databaseName> command. Then, run the db.dropDatabase() command.

db.dropDatabase()

The console will acknowledge which database has been deleted:

LibraryDB> db.dropDatabase()
{ ok: 1, dropped: 'LibraryDB' }

In this section, you have gained proficiency in working with MongoDB databases and mastering the essential operations. You have learned how to create or switch to a database, list available databases, create collections, insert, query, update, and delete data, as well as drop a database when needed.

Conclusion

Congratulations on completing this basic introduction to MongoDB! It has provided you with a solid starting point. To further enhance your skills, practice is key. In the next guide, you will explore how to create and interact with MongoDB using JavaScript, enabling you to seamlessly integrate it with your applications.

Did you find this article valuable?

Support Web3Dave by becoming a sponsor. Any amount is appreciated!