HTML Links - Different Colors


An HTML link is displayed in a different color depending on whether it has been visited, is unvisited, or is active.


HTML Link Colors

By default, a link will appear like this (in all browsers):

  • An unvisited link is underlined and blue
  • A visited link is underlined and purple
  • An active link is underlined and red

You can change the link state colors, by using CSS:

Example

Here, an unvisited link will be green with no underline. A visited link will be pink with no underline. An active link will be yellow and underlined. In addition, when mousing over a link (a:hover) it will become red and underlined:

<style>
a:link {
  color: green;
  background-color: transparent;
  text-decoration: none;
}

a:visited {
  color: pink;
  background-color: transparent;
  text-decoration: none;
}

a:hover {
  color: red;
  background-color: transparent;
  text-decoration: underline;
}

a:active {
  color: yellow;
  background-color: transparent;
  text-decoration: underline;
}
</style>


Link Buttons

A link can also be styled as a button, by using CSS:

Example

<style>
a:link, a:visited {
  background-color: #f44336;
  color: white;
  padding: 15px 25px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
}

a:hover, a:active {
  background-color: red;
}
</style>

To learn more about CSS, go to our .


HTML Link Tags

Tag Description
Defines a hyperlink

For a complete list of all available HTML tags, visit our .


 
[+:

MongoDB is a document database. It stores data in a type of JSON format called BSON.

If you are unfamiliar with JSON, check out our .

A record in MongoDB is a document, which is a data structure composed of key value pairs similar to the structure of JSON objects.

A MongoDB Document

Records in a MongoDB database are called documents, and the field values may include numbers, strings, booleans, arrays, or even nested documents.

Example Document

{
	title: "Post Title 1",
	body: "Body of post.",
	category: "News",
	likes: 1,
	tags: ["news", "events"],
	date: Date()
}

Learning by Examples

Our "Show MongoDB" tool makes it easy to demonstrate MongoDB. It shows both the code and the result.

Example

Find all documents that have a category of "news".

db.posts.find( {category: "News"} )

Learning by Exercises

MongoDB HOME
 

MongoDB

MongoDB is a document database and can be installed locally or hosted in the cloud.


SQL vs Document Databases

SQL databases are considered relational databases. They store related data in separate tables. When data is needed, it is queried from multiple tables to join the data back together.

MongoDB is a document database which is often referred to as a non-relational database. This does not mean that relational data cannot be stored in document databases. It means that relational data is stored differently. A better way to refer to it is as a non-tabular database.

MongoDB stores data in flexible documents. Instead of having multiple tables you can simply keep all of your related data together. This makes reading your data very fast.

You can still have multiple groups of data too. In MongoDB, instead of tables these are called collections.


Local vs Cloud Database

MongoDB can be installed locally, which will allow you to host your own MongoDB server on your hardware. This requires you to manage your server, upgrades, and any other maintenance.

You can download and use the MongoDB open source on your hardware for free.

However, for this course we are going to use MongoDB Atlas, a cloud database platform. This is much easier than hosting your own local database.

To be able to experiment with the code examples, you will need access to a MongoDB database.

Sign up for a free account to get started.


Creating a Cluster

After you have created your account, set up a free "Shared Cluster" then choose your preferred cloud provider and region.

By default, MongoDB Atlas is completely locked down and has no external access.

You will need to set up a user and add your IP address to the list of allowed IP addresses.

Under "Database Access", create a new user and keep track of the username and password.

Next, under "Network Access", add your current IP address to allow access from your computer.


Install MongoDB Shell (mongosh)

There are many ways to connect to your MongoDB database.

We will start by using the MongoDB Shell, mongosh.

Use the to install mongosh on your operating system.

To verify that it has been installed properly, open your terminal and type:

mongosh --version

You should see that the latest verion is installed.

The version used in this tutorial is v1.3.1.


Connect to the database

To connect to your database, you will need your database specific connection string.

In the MongoDB Atlas dashboard, under "Databases", click the "Connect" button for your Cluster.

Next, choose "Connect with the MongoDB Shell".

Copy your connection string.

Example

Your connection string should look similar to this:

mongosh "mongodb+srv://cluster0.ex4ht.mongodb.net/myFirstDatabase" --apiVersion 1 --username YOUR_USER_NAME

Paste your connection string into your terminal and press enter.

You will be prompted to enter your database user password that you created earlier.

You are now connected to the database!


What Next?

In the following sections we will use 'mongosh' to create, read, update, and delete (CRUD) items in your database.

After getting the basics down, we will move on to using MongoDB with other backend technologies like Node.js.


 
MongoDB Get Started
 

MongoDB Query API

The is the way you will interact with your data.

The MongoDB Query API can be used two ways:

  • CRUD Operations
  • Aggregation Pipelines

MongoDB Query API Uses

You can use the MongoDB Query API to perform:

  • Adhoc queries with mongosh, Compass, VS Code, or a MongoDB driver for the programming language you use.
  • Data transformations using aggregation pipelines.
  • Document join support to combine data from different collections.
  • Graph and geospatial queries.
  • Full-text search.
  • Indexing to improve MongoDB query performance.
  • Time series analysis.

Let's !


 
MongoDB Query API
 

Create Database using mongosh

After connecting to your database using mongosh, you can see which database you are using by typing db in your terminal.

If you have used the connection string provided from the MongoDB Atlas dashboard, you should be connected to the myFirstDatabase database.


Show all databases

To see all available databases, in your terminal type show dbs.

Notice that myFirstDatabase is not listed. This is because the database is empty. An empty database is essentially non-existant.


Change or Create a Database

You can change or create a new database by typing use then the name of the database.

Example

Create a new database called "blog":

use blog

We are now in the blog database.

Remember: In MongoDB, a database is not actually created until it gets content!


 
MongoDB Create Database
 

Create Collection using mongosh

There are 2 ways to create a collection.

Method 1

You can create a collection using the createCollection() database method.

Example

db.createCollection("posts")

Method 2

You can also create a collection during the insert process.

Example

We are here assuming object is a valid JavaScript object containing post data:

db.posts.insertOne(object)

This will create the "posts" collection if it does not already exist.

Remember: In MongoDB, a collection is not actually created until it gets content!


 
MongoDB Create Collection
 

Insert Documents

There are 2 methods to insert documents into a MongoDB database.

insertOne()

To insert a single document, use the insertOne() method.

This method inserts a single object into the database.

Note: When typing in the shell, after opening an object with curly braces "{" you can press enter to start a new line in the editor without executing the command. The command will execute when you press enter after closing the braces.

Example

db.posts.insertOne({
  title: "Post Title 1",
  body: "Body of post.",
  category: "News",
  likes: 1,
  tags: ["news", "events"],
  date: Date()
})

Note: If you try to insert documents into a collection that does not exist, MongoDB will create the collection automatically.

insertMany()

To insert multiple documents at once, use the insertMany() method.

This method inserts an array of objects into the database.

Example

db.posts.insertMany([  
  {
    title: "Post Title 2",
    body: "Body of post.",
    category: "Event",
    likes: 2,
    tags: ["news", "events"],
    date: Date()
  },
  {
    title: "Post Title 3",
    body: "Body of post.",
    category: "Technology",
    likes: 3,
    tags: ["news", "events"],
    date: Date()
  },
  {
    title: "Post Title 4",
    body: "Body of post.",
    category: "Event",
    likes: 4,
    tags: ["news", "events"],
    date: Date()
  }
])

 

 
MongoDB Insert
 

Find Data

There are 2 methods to find and select data from a MongoDB collection, find() and findOne().

find()

To select data from a collection in MongoDB, we can use the find() method.

This method accepts a query object. If left empty, all documents will be returned.

Example

db.posts.find()

findOne()

To select only one document, we can use the findOne() method.

This method accepts a query object. If left empty, it will return the first document it finds.

Note: This method only returns the first match it finds.

Example

db.posts.findOne()

Querying Data

To query, or filter, data we can include a query in our find() or findOne() methods.

Example

db.posts.find( {category: "News"} )

Projection

Both find methods accept a second parameter called projection.

This parameter is an object that describes which fields to include in the results.

Note: This parameter is optional. If omitted, all fields will be included in the results.

Example

This example will only display the title and date fields in the results.

db.posts.find({}, {title: 1, date: 1})

Notice that the _id field is also included. This field is always included unless specifically excluded.

We use a 1 to include a field and 0 to exclude a field.

Example

This time, let's exclude the _id field.

db.posts.find({}, {_id: 0, title: 1, date: 1})

Note: You cannot use both 0 and 1 in the same object. The only exception is the _id field. You should either specify the fields you would like to include or the fields you would like to exclude.

Let's exclude the date category field. All other fields will be included in the results.

Example

db.posts.find({}, {category: 0})

We will get an error if we try to specify both 0 and 1 in the same object.

Example

db.posts.find({}, {title: 1, date: 0})

 

 
MongoDB Find
 

Update Document

To update an existing document we can use the updateOne() or updateMany() methods.

The first parameter is a query object to define which document or documents should be updated.

The second parameter is an object defining the updated data.


updateOne()

The updateOne() method will update the first document that is found matching the provided query.

Let's see what the "like" count for the post with the title of "Post Title 1":

Example

db.posts.find( { title: "Post Title 1" } ) 

Now let's update the "likes" on this post to 2. To do this, we need to use the $set operator.

Example

db.posts.updateOne( { title: "Post Title 1" }, { $set: { likes: 2 } } ) 

Check the document again and you'll see that the "like" have been updated.

Example

db.posts.find( { title: "Post Title 1" } ) 

Insert if not found

If you would like to insert the document if it is not found, you can use the upsert option.

Example

Update the document, but if not found insert it:

db.posts.updateOne( 
  { title: "Post Title 5" }, 
  {
    $set: 
      {
        title: "Post Title 5",
        body: "Body of post.",
        category: "Event",
        likes: 5,
        tags: ["news", "events"],
        date: Date()
      }
  }, 
  { upsert: true }
)

updateMany()

The updateMany() method will update all documents that match the provided query.

Example

Update likes on all documents by 1. For this we will use the $inc (increment) operator:

db.posts.updateMany({}, { $inc: { likes: 1 } })

Now check the likes in all of the documents and you will see that they have all been incremented by 1.


 
MongoDB Update
 

Delete Documents

We can delete documents by using the methods deleteOne() or deleteMany().

These methods accept a query object. The matching documents will be deleted.


deleteOne()

The deleteOne() method will delete the first document that matches the query provided.

Example

db.posts.deleteOne({ title: "Post Title 5" })

deleteMany()

The deleteMany() method will delete all documents that match the query provided.

Example

db.posts.deleteMany({ category: "Technology" })

 

 
MongoDB Delete
 

MongoDB Query Operators

There are many query operators that can be used to compare and reference document fields.

Comparison

The following operators can be used in queries to compare values:

  • $eq: Values are equal
  • $ne: Values are not equal
  • $gt: Value is greater than another value
  • $gte: Value is greater than or equal to another value
  • $lt: Value is less than another value
  • $lte: Value is less than or equal to another value
  • $in: Value is matched within an array

Logical

The following operators can logically compare multiple queries.

  • $and: Returns documents where both queries match
  • $or: Returns documents where either query matches
  • $nor: Returns documents where both queries fail to match
  • $not: Returns documents where the query does not match

Evaluation

The following operators assist in evaluating documents.

  • $regex: Allows the use of regular expressions when evaluating field values
  • $text: Performs a text search
  • $where: Uses a JavaScript expression to match documents

 
MongoDB Query Operators
 

MongoDB Update Operators

There are many update operators that can be used during document updates.

Fields

The following operators can be used to update fields:

  • $currentDate: Sets the field value to the current date
  • $inc: Increments the field value
  • $rename: Renames the field
  • $set: Sets the value of a field
  • $unset: Removes the field from the document

Array

The following operators assist with updating arrays.

  • $addToSet: Adds distinct elements to an array
  • $pop: Removes the first or last element of an array
  • $pull: Removes all elements from an array that match the query
  • $push: Adds an element to an array

 
MongoDB Update Operators
 

Aggregation Pipelines

Aggregation operations allow you to group, sort, perform calculations, analyze data, and much more.

Aggregation pipelines can have one or more "stages". The order of these stages are important. Each stage acts upon the results of the previous stage.

Example

db.posts.aggregate([
  // Stage 1: Only find documents that have more than 1 like
  {
    $match: { likes: { $gt: 1 } }
  },
  // Stage 2: Group documents by category and sum each categories likes
  {
    $group: { _id: "$category", totalLikes: { $sum: "$likes" } }
  }
])

Sample Data

To demonstrate the use of stages in a aggregation pipeline, we will load sample data into our database.

From the MongoDB Atlas dashboard, go to Databases. Click the ellipsis and select "Load Sample Dataset". This will load several sample datasets into your database.

In the next sections we will explore several aggregation pipeline stages in more detail using this sample data.


 
 

Aggregation Pipelines

Aggregation operations allow you to group, sort, perform calculations, analyze data, and much more.

Aggregation pipelines can have one or more "stages". The order of these stages are important. Each stage acts upon the results of the previous stage.

Example

db.posts.aggregate([
  // Stage 1: Only find documents that have more than 1 like
  {
    $match: { likes: { $gt: 1 } }
  },
  // Stage 2: Group documents by category and sum each categories likes
  {
    $group: { _id: "$category", totalLikes: { $sum: "$likes" } }
  }
])

Sample Data

To demonstrate the use of stages in a aggregation pipeline, we will load sample data into our database.

From the MongoDB Atlas dashboard, go to Databases. Click the ellipsis and select "Load Sample Dataset". This will load several sample datasets into your database.

In the next sections we will explore several aggregation pipeline stages in more detail using this sample data.


 
MongoDB Aggregations
 

Aggregation $group

This aggregation stage groups documents by the unique _id expression provided.

Don't confuse this _id expression with the _id ObjectId provided to each document.

Example

In this example, we are using the "sample_airbnb" database loaded from our sample data in the section.

db.listingsAndReviews.aggregate(
    [ { $group : { _id : "$property_type" } } ]
)

This will return the distinct values from the property_type field.


 
$group
 

Aggregation $limit

This aggregation stage limits the number of documents passed to the next stage.

Example

In this example, we are using the "sample_mflix" database loaded from our sample data in the section.

db.movies.aggregate([ { $limit: 1 } ])

This will return the 1 movie from the collection.


 
$limit

MongoDB Aggregation $project

 

Aggregation $project

This aggregation stage passes only the specified fields along to the next aggregation stage.

This is the same projection that is used with the find() method.

Example

In this example, we are using the "sample_restaurants" database loaded from our sample data in the section.

db.restaurants.aggregate([
  {
    $project: {
      "name": 1,
      "cuisine": 1,
      "address": 1
    }
  },
  {
    $limit: 5
  }
])

This will return the documents but only include the specified fields.

Notice that the _id field is also included. This field is always included unless specifically excluded.

We use a 1 to include a field and 0 to exclude a field.

Note: You cannot use both 0 and 1 in the same object. The only exception is the _id field. You should either specify the fields you would like to include or the fields you would like to exclude.


 
$project

MongoDB Aggregation $sort

 

Aggregation $sort

This aggregation stage groups sorts all documents in the specified sort order.

Remember that the order of your stages matters. Each stage only acts upon the documents that previous stages provide.

Example

In this example, we are using the "sample_airbnb" database loaded from our sample data in the section.

db.listingsAndReviews.aggregate([ 
  { 
    $sort: { "accommodates": -1 } 
  },
  {
    $project: {
      "name": 1,
      "accommodates": 1
    }
  },
  {
    $limit: 5
  }
])

This will return the documents sorted in descending order by the accommodates field.

The sort order can be chosen by using 1 or -1. 1 is ascending and -1 is descending.


 
$sort

MongoDB Aggregation $match

 

Aggregation $match

This aggregation stage behaves like a find. It will filter documents that match the query provided.

Using $match early in the pipeline can improve performance since it limits the number of documents the next stages must process.

Example

In this example, we are using the "sample_airbnb" database loaded from our sample data in the section.

db.listingsAndReviews.aggregate([ 
  { $match : { property_type : "House" } },
  { $limit: 2 },
  { $project: {
    "name": 1,
    "bedrooms": 1,
    "price": 1
  }}
])

This will only return documents that have the property_type of "House".


 
$match

MongoDB Aggregation $addFields

 

Aggregation $addFields

This aggregation stage adds new fields to documents.

Example

In this example, we are using the "sample_restaurants" database loaded from our sample data in the section.

db.restaurants.aggregate([
  {
    $addFields: {
      avgGrade: { $avg: "$grades.score" }
    }
  },
  {
    $project: {
      "name": 1,
      "avgGrade": 1
    }
  },
  {
    $limit: 5
  }
])

This will return the documents along with a new field, avgGrade, which will contain the average of each restaurants grades.score.


 
$addFields

MongoDB Aggregation $count

 

Aggregation $count

This aggregation stage counts the total amount of documents passed from the previous stage.

Example

In this example, we are using the "sample_restaurants" database loaded from our sample data in the section.

db.restaurants.aggregate([
  {
    $match: { "cuisine": "Chinese" }
  },
  {
    $count: "totalChinese"
  }
])

This will return the number of documents at the $count stage as a field called "totalChinese".


 
$count

MongoDB Aggregation $lookup

 

Aggregation $lookup

This aggregation stage performs a left outer join to a collection in the same database.

There are four required fields:

  • from: The collection to use for lookup in the same database
  • localField: The field in the primary collection that can be used as a unique identifier in the from collection.
  • foreignField: The field in the from collection that can be used as a unique identifier in the primary collection.
  • as: The name of the new field that will contain the matching documents from the from collection.

Example

In this example, we are using the "sample_mflix" database loaded from our sample data in the section.

db.comments.aggregate([
  {
    $lookup: {
      from: "movies",
      localField: "movie_id",
      foreignField: "_id",
      as: "movie_details",
    },
  },
  {
    $limit: 1
  }
])

This will return the movie data along with each comment.


 
$lookup

MongoDB Aggregation $out

 

Aggregation $out

This aggregation stage writes the returned documents from the aggregation pipeline to a collection.

The $out stage must be the last stage of the aggregation pipeline.

Example

In this example, we are using the "sample_airbnb" database loaded from our sample data in the section.

db.listingsAndReviews.aggregate([
  {
    $group: {
      _id: "$property_type",
      properties: {
        $push: {
          name: "$name",
          accommodates: "$accommodates",
          price: "$price",
        },
      },
    },
  },
  { $out: "properties_by_type" },
])

The first stage will group properties by the property_type and include the name, accommodates, and price fields for each. The $out stage will create a new collection called properties_by_type in the current database and write the resulting documents into that collection.


 
$out
 

Indexing & Search

MongoDB Atlas comes with a full-text search engine that can be used to search for documents in a collection.

is powered by Apache Lucene.


Creating an Index

We'll use the Atlas dashboard to create an index on the "sample_mflix" database from the sample data that we loaded in the section.

  1. From the Atlas dashboard, click on your Cluster name then the Search tab.
  2. Click on the Create Search Index button.
  3. Use the Visual Editor and click Next.
  4. Name your index, choose the Database and Collection you want to index and click Next.
    • If you name your index "default" you will not have to specify the index name in the $search pipeline stage.
    • Choose the sample_mflix database and the movies collection.
  5. Click Create Search Index and wait for the index to complete.

Running a Query

To use our search index, we will use the $search operator in our aggregation pipeline.

Example

db.movies.aggregate([
  {
    $search: {
      index: "default", // optional unless you named your index something other than "default"
      text: {
        query: "star wars",
        path: "title"
      },
    },
  },
  {
    $project: {
      title: 1,
      year: 1,
    }
  }
])

The first stage of this aggregation pipeline will return all documents in the movies collection that contain the word "star" or "wars" in the title field.

The second stage will project the title and year fields from each document.


 
MongoDB Indexing/Search
 

Schema Validation

By default MongoDB has a flexible schema. This means that there is no strict schema validation set up initially.

Schema validation rules can be created in order to ensure that all documents a collection share a similar structure.


Schema Validation

MongoDB supports validation. The $jsonSchema operator allows us to define our document structure.

Example

db.createCollection("posts", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: [ "title", "body" ],
      properties: {
        title: {
          bsonType: "string",
          description: "Title of post - Required."
        },
        body: {
          bsonType: "string",
          description: "Body of post - Required."
        },
        category: {
          bsonType: "string",
          description: "Category of post - Optional."
        },
        likes: {
          bsonType: "int",
          description: "Post like count. Must be an integer - Optional."
        },
        tags: {
          bsonType: ["string"],
          description: "Must be an array of strings - Optional."
        },
        date: {
          bsonType: "date",
          description: "Must be a date - Optional."
        }
      }
    }
  }
})

This will create the posts collection in the current database and specify the JSON Schema validation requirements for the collection.


 
MongoDB Validation
 

MongoDB Data API

The can be used to query and update data in a MongoDB database without the need for language specific drivers.

Language drivers should be used when possible, but the MongoDB Data API comes in handy when drivers are not available or drivers are overkill for the application.


Read & Write with the MongoDB Data API

The MongoDB Data API is a pre-configured set of HTTPS endpoints that can be used to read and write data to a MongoDB Atlas database.

With the MongoDB Data API, you can create, read, update, delete, or aggregate documents in a MongoDB Atlas database.


Cluster Configuration

In order to use the Data API, you must first enable the functionality from the Atlas UI.

From the MongoDB Atlas dashboard, navigate to Data API in the left menu.

Select the data source(s) you would like to enable the API on and click Enable the Data API.


Access Level

By default, no access is granted. Select the access level you'd like to grant the Data API. The choices are: No Access, Read Only, Read and Write, or Custom Access.


Data API Key

In order to authenticate with the Data API, you must first create a Data API key.

Click Create API Key, enter a name for the key, then click Generate API Key.

Be sure to copy the API key and save it somewhere safe. You will not get another chance to see this key again.


Sending a Data API Request

We can now use the Data API to send a request to the database.

In the next example, we'll use curl to find the first document in the movies collection of our sample_mflix database. We loaded this sample data in the section.

To run this example, you'll need your App Id, API Key, and Cluster name.

You can find your App Id in the URL Endpoint field of the Data API page in the MongoDB Atlas UI.

Example

curl --location --request POST 'https://data.mongodb-api.com/app//endpoint/data/v1/action/findOne' 
--header 'Content-Type: application/json' 
--header 'Access-Control-Request-Headers: *' 
--header 'api-key: ' 
--data-raw '{
    "dataSource":"",
    "database":"sample_mflix",
    "collection":"movies",
    "projection": {"title": 1}
}'

Data API Endpoints

In the previous example, we used the findOne endpoint in our URL.

There are several endpoints available for use with the Data API.

All endpoints start with the Base URL: https://data.mongodb-api.com/app//endpoint/data/v1/action/


Find a Single Document

Endpoint

POST Base_URL/findOne

The findOne endpoint is used to find a single document in a collection.

Request Body

Example

{
  "dataSource": "",
  "database": "",
  "collection": "",
  "filter": ,
  "projection": 
}

Find Multiple Documents

Endpoint

POST Base_URL/find

The find endpoint is used to find multiple documents in a collection.

Request Body

Example

{
  "dataSource": "",
  "database": "",
  "collection": "",
  "filter": ,
  "projection": ,
  "sort": ,
  "limit": ,
  "skip": 
}

Insert a Single Document

Endpoint

POST Base_URL/insertOne

The insertOne endpoint is used to insert a single document into a collection.

Request Body

Example

{
  "dataSource": "",
  "database": "",
  "collection": "",
  "document": 
}

Insert Multiple Documents

Endpoint

POST Base_URL/insertMany

The insertMany endpoint is used to insert multiple documents into a collection.

Request Body

Example

{
  "dataSource": "",
  "database": "",
  "collection": "",
  "documents": [, , ...]
}

Update a Single Document

Endpoint

POST Base_URL/updateOne

Request Body

Example

{
  "dataSource": "",
  "database": "",
  "collection": "",
  "filter": ,
  "update": ,
  "upsert": true|false
}

Update Multiple Documents

Endpoint

POST Base_URL/updateMany

Request Body

Example

{
  "dataSource": "",
  "database": "",
  "collection": "",
  "filter": ,
  "update": ,
  "upsert": true|false
}

Delete a Single Document

Endpoint

POST Base_URL/deleteOne

Request Body

Example

{
  "dataSource": "",
  "database": "",
  "collection": "",
  "filter": 
}

Delete Multiple Documents

Endpoint

POST Base_URL/deleteMany

Request Body

Example

{
  "dataSource": "",
  "database": "",
  "collection": "",
  "filter": 
}

Aggregate Documents

Endpoint

POST Base_URL/aggregate

Request Body

Example

{
  "dataSource": "",
  "database": "",
  "collection": "",
  "pipeline": [, ...]
}

 
MongoDB Data API
 

MongoDB Drivers

The MongoDB Shell (mongosh) is great, but generally you will need to use MongoDB in your application. To do this, MongoDB has many language drivers.

The language drivers allow you to interact with your MongoDB database using the methods you've learned so far in `mongosh` but directly in your application.

These are the current officially supported drivers:

 

There are other as well.

Let's see how to use the drivers using next.


 
MongoDB Drivers
 

Node.js Database Interaction

For this tutorial, we will use a MongoDB Atlas database. If you don't already have a MongoDB Atlas account, you can create one for free at .

We will also use the "sample_mflix" database loaded from our sample data in the section.


MongoDB Node.js Driver Installation

To use MongoDB with Node.js, you will need to install the mongodb package in your Node.js project.

Use the following command in your terminal to install the mongodb package:

npm install mongodb

We can now use this package to connect to a MongoDB database.

Create an index.js file in your project directory.

index.js

const { MongoClient } = require('mongodb');

Connection String

In order to connect to our MongoDB Atlas database, we'll need to get our connection string from the Atlas dashboard.

Go to Database then click the CONNECT button on your Cluster.

Choose Connect your application then copy your connection string.

Example: mongodb+srv://:@.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

You will need to replace the , , and with your MongoDB Atlas username, password, and cluster string.


Connecting to MongoDB

Let's add to our index.js file.

index.js

const { MongoClient } = require('mongodb');

const uri = "";
const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    const db = client.db('sample_mflix');
    const collection = db.collection('movies');

    // Find the first document in the collection
    const first = await collection.findOne();
    console.log(first);
  } finally {
    // Close the database connection when finished or an error occurs
    await client.close();
  }
}
run().catch(console.error);

Run this file in your terminal.

node index.js

You should see the first document logged to the console.


CRUD & Document Aggregation

Just as we did using mongosh, we can use the MongoDB Node.js language driver to create, read, update, delete, and aggregate documents in the database.

Expanding on the previous example, we can replace the collection.findOne() with find(), insertOne(), insertMany(), updateOne(), updateMany(), deleteOne(), deleteMany(), or aggregate().

Give some of those a try.


 
MongoDB Node.js Driver
 

MongoDB Charts

lets you visualize your data in a simple, intuitive way.


MongoDB Charts Setup

From the MongoDB Atlas dashboard, go to the Charts tab.

If you've never used Charts before, click the Activate Now button. This will take about 1 minute to complete.

You'll see a new dashboard. Click the dashboard name to open it.


Creating a Chart

Create a new chart by clicking the Add Chart button.

Visually creating a chart is intuitive. Select the data sources that you want to use.


Example:

In this example, we are using the "sample_mflix" database loaded from our sample data in the section.

Under Data Source, select the Movies collection.

Let's visualize how many movies were released in each year.

Drag the Year field to the Y Axis field and set the Bin Size to 1.

Drag the _id field to the X Axis field and make sure COUNT is selected for the Aggregate.

You should now see a bar chart with the number of movies released in each year.

 

MongoDB Charts

MongoDB Exercises

 

You can test your MongoDB skills with W3Schools' Exercises.


Exercises

We have gathered a variety of MongoDB exercises (with answers) for each MongoDB Chapter.

Try to solve an exercise by editing some code, or show the answer to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start Mongodb Exercises

Good luck!

 

If you don't know MongoDB, we suggest that you read our from scratch.


 

 
MongoDB Exercises

Login
ADS CODE