Knowledgebase

Install and Configure MongoDB Database Server On Ubuntu 20.04 Print

  • 0

Introduction

MongoDB is a popular database for building modern apps. It is a scalable NoSQL database that allows you to store data in separate JSON (JavaScript Object Notation) documents inside a collection instead of using table rows and columns as traditionally done in relational databases. This dynamic schema offers you great flexibility since you can add or delete fields on different MongoDB documents without impacting an existing collection.

In addition, MongoDB is a high-performance database for handling large amounts of unstructured data providing you with the freedom to store multiple data types. These include string, integer, boolean, double, array, object, date, binary data, and more. When it comes to high availability, MongoDB uses replica-sets to provide data redundancy in a clustered server environment.

Built for the cloud, MongoDB is highly scalable using a native scale-out architecture that allows you to shard data in situations where horizontal scaling is inevitable. MongoDB is not suitable for tightly coupled database schema and applications that rely on the ACID (atomicity, consistency, isolation, durability) principles(For instance, banking/financial applications). However, it is a good option for setting up e-commerce websites, catalogs, blogs, geospatial data, social networking sites, real-time analytics, and more.

eBay uses MongoDB in metadata storage, merchandise categorization, and search suggestions on customer-facing applications. Also, McAfee has fully implemented the MongoDB architecture in analyzing big data and, thus, protects customers from cyber threats. In this guide, you'll install, configure, and test the CRUD (Create, Read, Update, and Delete) operations provided by the MongoDB Community Edition on Ubuntu 20.04 server.

Prerequisite

To follow along with this guide, make sure you have the following:

1. Install the MongoDB Server

In this step, you'll install the MongoDB database server by downloading the required files from the official MongoDB repository. SSH to your server and use the Linux wget command to pull and add the mongodb-org package GPG Key into your machine.

$ wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

The operation should respond with an OK message.

OK

Next, create a list file for your MongoDB package under the /etc/apt/sources.list.d directory.

$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

Then, refresh the local package information index by issuing the following command.

$ sudo apt update

With the package information database updated, execute the following command to install the latest stable version of the mongodb-org package.

$ sudo apt-get install -y mongodb-org

Once you've finished, the installation script creates a data directory in the following location.

/var/lib/mongodb 

Also, MongoDB reports activity logs to a mongod.log file which you can locate from the location below.

/var/log/mongodb

The MongoDB package runs under the service mongod. Use the following systemctl commands to manage it.

  • Check the MongoDB status:

      $ sudo systemctl status mongod
  • Start the MongoDB service:

      $ sudo systemctl start mongod
  • Enable the MongoDB service to be started on boot:

      $ sudo systemctl enable mongod
  • Stop the MongoDB service:

      $ sudo systemctl stop mongod
  • Restart the MongoDB service. For instance after making configuration changes:

      $ sudo systemctl restart mongod

You can tweak MongoDB settings by modifying the configuration file in the location below. For instance, you can define a different data or log directory.

/etc/mongod.conf

MongoDB loads the configuration settings from the /etc/mongod.conf file when starting up. Therefore, you should always restart the MongoDB instance in case you make any configuration changes to the file. In the next step, you'll secure MongoDB server by changing some settings in the configuration file.

2. Configure Access Control on the MongoDB Server

By default, the MongoDB service is not secure. You must enable access control and restrict read/write access to the server. To do this, connect to the MongoDB server through the mongosh shell.

$ mongosh

You should now be logged in to the MongoDB server. You'll get some startup warnings when the service loads since you've not yet configured the MongoDB authentication.

Current Mongosh Log ID: 612e0b0da174636a8c40e2de
...
Using MongoDB:          5.0.2
Using Mongosh:          1.0.5
...
test >

Once you receive the test > prompt, switch to the admin database.

test > use admin

Output.

switched to db admin

Then, execute the following command to create an administrative user with superuser/root privileges.

admin> db.createUser(
      {
        user: "mongo_db_admin",
        pwd: passwordPrompt(),
        roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "root"]
      }
      ) 

Enter your desired password and press Enter to proceed. Then, exit from the MongoDB command-line interface by issuing the command below.

admin> quit

Next, open the MongoDB configuration file using the nano text editor to enable authorization which is disabled by default.

$ sudo nano /etc/mongod.conf

Locate the security directive. By default, it should be commented out with # sign as you can see below.

...

#security:
...

Change the value of the #security: setting to the following option.

security:
  authorization: enabled

Save and close the file. Then, restart the MongoDB server to effect the new configuration changes.

$  sudo systemctl restart mongod

You've now successfully installed and secured the MongoDb server. In the next step, you will connect to the server and create a database.

3. Create a MongoDB Database

Just like in other SQL database management systems, MongoDB allows you to use the mongosh command-line tool to interact with database objects. This is a standalone package written in Javascript and Node.js. In this step, you'll use the mongosh utility to create a new database.

Before you do this, use the following table to familiarize yourself with some MongoDB terms as they compare with the basic SQL concepts to avoid confusion as you continue testing the rest of the guide.

  • MySQL has Database, Table, Column, and Record.
  • MongoDB entities are: Database, Collection, Field, and Document.

Once you've grasped the concept of the terms used in MongoDB to name database objects, connect to your MongoDB instance by establishing a new mongosh session by executing the following command. The mongo_db_admin is the superuser/root account that you created earlier.

$ mongosh -u mongo_db_admin -p --authenticationDatabase admin

Enter the mongo_db_admin password and press Enter to continue. By default, the mongosh shell should display the following output meaning you're connected to a test database. You should no longer receive the startup authorization warnings since you're now properly authenticated into the database server.

test>

Create a new e_commerce database. Please note MongoDB does not support the CREATE DATABASE command. Instead, to set up a new database, simply switch the context to an empty database by executing the use command. To create the e_commerce database, run the following command.

test> use e_commerce

Confirm the response below to make sure you've created and switched to the new database.

switched to db e_commerce
e_commerce>

Please note how the mongosh prompt changes from test> to e_commerce>. In other words, MongoDB prefixes the prompt with the name of your current database. This is very important, especially when you're executing dangerous commands, since you can verify your selected database. In the next step, you'll create a new MongoDB collection and learn how to insert JSON documents into it.

4. Create a Collection and Insert Documents in MongoDB

MongoDB handles multiple documents(records) by merging them into a single collection(A replica of a table in SQL). In this step, you'll insert both single and multiple documents in a new collection. Start by inserting a single document(record) into a new products collection using the db.EXAMPLE_COLLECTION.insertOne function as shown below.

e_commerce> db.products.insertOne(
              {"product_id" : 1,
                "product_name" : "VPS HOSTING",
                "retail_price" : 5.36    
              }
            )

You should get the following acknowledgment. You've now inserted a document into the products collection and received a new unique identifier (insertedId). In this case, the value of the key is 612dd87d5607a039586f5da9.

{
  acknowledged: true,
  insertedId: ObjectId("612dd87d5607a039586f5da9")
}

For the basis of better understanding, the above command is equivalent to the following SQL statement.

mysql> CREATE TABLE products(
           product_id INT,
           product_name VARCHAR(50),
           retail_price DOUBLE               
       );

       INSERT INTO products (product_id, product_name, retail_price) VALUES (1, 'VPS HOSTING', 5.36);

In MongoDB, you can insert multiple documents in the same collection by using the insertMany statement and wrapping the documents in a JSON array [...]. For instance, to insert 3 additional records into the products collection, run the following command.

e_commerce> db.products.insertMany([
            {"product_id" : 2,
              "product_name" : "DEDICATED CLOUD",
              "retail_price" : 60.35    
            },
            {"product_id" : 3,
              "product_name" : "MANAGED DATABASES",
              "retail_price" : 10.20    
            },
            {"product_id" : 4,
              "product_name" : "BARE METAL HOSTING",
              "retail_price" : 120.0 
            }  
           ]);

Confirm the output below, which acknowledges that you've inserted all 3 documents successfully.

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("612dd95f5607a039586f5daa"),
    '1': ObjectId("612dd95f5607a039586f5dab"),
    '2': ObjectId("612dd95f5607a039586f5dac")
  }
}

Once a collection and some documents are in place, you'll now locate documents using some search patterns in the next step.

5. Find Documents in a MongoDB Collection

If you have a huge list of documents, for instance, thousands or millions of records in a single MongoDB collection, locating a single record manually can be a tedious task. Luckily, MongoDB offers a very important function for finding documents. For instance, to list all the documents from the products collection, execute the following db.EXAMPLE_COLLECTION.find() command.

e_commerce> db.products.find()

You should now see a list of all documents and products' information as shown below.

[
  {
    _id: ObjectId("612dd87d5607a039586f5da9"),
    product_id: 1,
    product_name: 'VPS HOSTING',
    retail_price: 5.36
  },
  {
    _id: ObjectId("612dd95f5607a039586f5daa"),
    product_id: 2,
    product_name: 'DEDICATED CLOUD',
    retail_price: 60.35
  },
  {
    _id: ObjectId("612dd95f5607a039586f5dab"),
    product_id: 3,
    product_name: 'MANAGED DATABASES',
    retail_price: 10.2
  },
  {
    _id: ObjectId("612dd95f5607a039586f5dac"),
    product_id: 4,
    product_name: 'BARE METAL HOSTING',
    retail_price: 120
  }
]

The db.products.find() command is the equivalent of SELECT * FROM products statement in SQL. Also, when returning records to a client application from the MongoDB database, you can choose to only return a subset of data by using the MongoDB limit() clause. For instance, to return only 2 records from the products collection, run the following command.

e_commerce> db.products.find().limit(2)

Output.

[
  {
    _id: ObjectId("612dd87d5607a039586f5da9"),
    product_id: 1,
    product_name: 'VPS HOSTING',
    retail_price: 5.36
  },
  {
    _id: ObjectId("612dd95f5607a039586f5daa"),
    product_id: 2,
    product_name: 'DEDICATED CLOUD',
    retail_price: 60.35
  }
]

To find a single document, enclose a filter parameter inside the find() function. For instance, to filter products using the product_id field, run the command below.

e_commerce> db.products.find({"product_id":2})

The above command displays a single document with a product_id of 2.

[
  {
    _id: ObjectId("612dd95f5607a039586f5daa"),
    product_id: 2,
    product_name: 'DEDICATED CLOUD',
    retail_price: 60.35
  }
]

The db.products.find({"product_id":2}) is the same as SELECT * FROM products where product_id = '2' statement in SQL. Also, you can filter products using the product_name field by executing the following command.

e_commerce> db.products.find({"product_name":"MANAGED DATABASES"})

Output.

[
  {
    _id: ObjectId("612dd95f5607a039586f5dab"),
    product_id: 3,
    product_name: 'MANAGED DATABASES',
    retail_price: 10.2
  }
]

You've now searched documents using some filters. Next, you'll update a record that matches a certain filter condition.

6. Update Existing Document in a MongoDB Collection

In a production environment, you'll encounter scenarios where you need to update existing MongoDB documents. To make changes to a single record, use the update and $set: {...} statements. For instance, run the command below to change the name of the {"product_id": 2, product_name: "DEDICATED CLOUD" product to SINGLE TENANT PRIVATE CLOUD.

e_commerce> db.products.update(
             {
               "product_id" : 2
             },
             {
               $set: {
                 "product_name" : "SINGLE TENANT PRIVATE CLOUD"
               }
             }
            )

Output:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

The above command is equivalent to UPDATE products SET product_name = 'SINGLE TENANT PRIVATE CLOUD' WHERE product_id = '2'; statement in SQL. When updating records, use a field that is part of a unique index. Confirm the product changes by searching the product details in the collection.

e_commerce> db.products.find({"product_id":2})

You've now updated the product's details, as shown below.

[
  {
    _id: ObjectId("612de1435607a039586f5dae"),
    product_id: 2,
    product_name: 'SINGLE TENANT PRIVATE CLOUD',
    retail_price: 60.35
  }
]

Apart from the $set: {...} statement, which completely replaces the value of a field, you can use the $inc: {...} statement to increment a field by a specific value. For instance, to effect a price change of $40 to the SINGLE TENANT PRIVATE CLOUD item with a product_id of 2, run the command below.

e_commerce> db.products.update(
             {
               "product_id" : 2
             },
             {
               $inc: {
                 retail_price: +40
               }
             }
            )

Make sure you get the following acknowledgment.

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Find the product again from the collection to confirm the new price change.

e_commerce> db.products.find({"product_id":2})

As you can confirm from the following output, you've successfully changed the retail_price to $100.35.

[
  {
    _id: ObjectId("612de1435607a039586f5dae"),
    product_id: 2,
    product_name: 'SINGLE TENANT PRIVATE CLOUD',
    retail_price: 100.35
  }
]

Apart from updating records, as you've seen above, you may delete a single document, empty an entire collection, or even delete the database in MongoDB, as you'll see next.

7. Delete a MongoDB Document, Collection, or a Database

In MongoDB, you can use the db.EXAMPLE_COLLECTION.deleteOne statement to remove a single document from a collection. This is useful in cases where you no longer want the record to appear in a collection. For instance, when you discontinue a product from your catalog.

To delete the {product_id: 1, product_name: 'VPS HOSTING'} document from the products collection, execute the command below.

e_commerce> db.products.deleteOne({"product_id" : 1});

Output.

{ acknowledged: true, deletedCount: 1 }

Also, you can use the deleteMany({}) command to remove all existing documents from a collection. This statement is equivalent to the TRUNCATE command in SQL. To delete all products from your products catalog collection, run the command below.

e_commerce> db.products.deleteMany({});

The following output verifies that you've successfully deleted 3 records from your products collection.

{ acknowledged: true, deletedCount: 3 }

If you now run a find() command against the products collection, you should now get an empty set.

e_commerce> db.products.find()

Output.

...
> use e_commerce

To delete an entire database, first execute the use command.

> use e_commerce

Output 1.

already on db e_commerce
e_commerce>

Output 2.

switched to db e_commerce
e_commerce>

Then, drop the database by executing the dropDatabase() statement.

e_commerce> db.dropDatabase() 

You've now deleted the database, and you should get the following output.

{ ok: 1, dropped: 'e_commerce' }

After executing all CRUD operations and other commands on the database, you can confirm that the MongoDB installation is now working as expected. You can now create more databases or add additional documents depending on the application you want to build using the MongoDB server.

Conclusion

In this guide, you've installed and configured the MongoDB package on the Ubuntu 20.04 server. You've also set up a new database and created a collection with several documents. Towards the end of the guide, you've performed all CRUD operations on the MongoDB collection. Use the knowledge in this guide to set up and secure your MongoDB server next time when working on your project.

Introduction MongoDB is a popular database for building modern apps. It is a scalable NoSQL database that allows you to store data in separate JSON (JavaScript Object Notation) documents inside a collection instead of using table rows and columns as traditionally done in relational databases. This dynamic schema offers you great flexibility since you can add or delete fields on different MongoDB documents without impacting an existing collection. In addition, MongoDB is a high-performance database for handling large amounts of unstructured data providing you with the freedom to store multiple data types. These include string, integer, boolean, double, array, object, date, binary data, and more. When it comes to high availability, MongoDB uses replica-sets to provide data redundancy in a clustered server environment. Built for the cloud, MongoDB is highly scalable using a native scale-out architecture that allows you to shard data in situations where horizontal scaling is inevitable. MongoDB is not suitable for tightly coupled database schema and applications that rely on the ACID (atomicity, consistency, isolation, durability) principles(For instance, banking/financial applications). However, it is a good option for setting up e-commerce websites, catalogs, blogs, geospatial data, social networking sites, real-time analytics, and more. eBay uses MongoDB in metadata storage, merchandise categorization, and search suggestions on customer-facing applications. Also, McAfee has fully implemented the MongoDB architecture in analyzing big data and, thus, protects customers from cyber threats. In this guide, you'll install, configure, and test the CRUD (Create, Read, Update, and Delete) operations provided by the MongoDB Community Edition on Ubuntu 20.04 server. Prerequisite To follow along with this guide, make sure you have the following: An Ubuntu 20.04 server. A sudo user. 1. Install the MongoDB Server In this step, you'll install the MongoDB database server by downloading the required files from the official MongoDB repository. SSH to your server and use the Linux wget command to pull and add the mongodb-org package GPG Key into your machine. $ wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add - The operation should respond with an OK message. OK Next, create a list file for your MongoDB package under the /etc/apt/sources.list.d directory. $ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list Then, refresh the local package information index by issuing the following command. $ sudo apt update With the package information database updated, execute the following command to install the latest stable version of the mongodb-org package. $ sudo apt-get install -y mongodb-org Once you've finished, the installation script creates a data directory in the following location. /var/lib/mongodb Also, MongoDB reports activity logs to a mongod.log file which you can locate from the location below. /var/log/mongodb The MongoDB package runs under the service mongod. Use the following systemctl commands to manage it. Check the MongoDB status: $ sudo systemctl status mongod Start the MongoDB service: $ sudo systemctl start mongod Enable the MongoDB service to be started on boot: $ sudo systemctl enable mongod Stop the MongoDB service: $ sudo systemctl stop mongod Restart the MongoDB service. For instance after making configuration changes: $ sudo systemctl restart mongod You can tweak MongoDB settings by modifying the configuration file in the location below. For instance, you can define a different data or log directory. /etc/mongod.conf MongoDB loads the configuration settings from the /etc/mongod.conf file when starting up. Therefore, you should always restart the MongoDB instance in case you make any configuration changes to the file. In the next step, you'll secure MongoDB server by changing some settings in the configuration file. 2. Configure Access Control on the MongoDB Server By default, the MongoDB service is not secure. You must enable access control and restrict read/write access to the server. To do this, connect to the MongoDB server through the mongosh shell. $ mongosh You should now be logged in to the MongoDB server. You'll get some startup warnings when the service loads since you've not yet configured the MongoDB authentication. Current Mongosh Log ID: 612e0b0da174636a8c40e2de ... Using MongoDB: 5.0.2 Using Mongosh: 1.0.5 ... test > Once you receive the test > prompt, switch to the admin database. test > use admin Output. switched to db admin Then, execute the following command to create an administrative user with superuser/root privileges. admin> db.createUser( { user: "mongo_db_admin", pwd: passwordPrompt(), roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "root"] } ) Enter your desired password and press ENTER to proceed. Then, exit from the MongoDB command-line interface by issuing the command below. admin> quit Next, open the MongoDB configuration file using the nano text editor to enable authorization which is disabled by default. $ sudo nano /etc/mongod.conf Locate the security directive. By default, it should be commented out with # sign as you can see below. ... #security: ... Change the value of the #security: setting to the following option. security: authorization: enabled Save and close the file. Then, restart the MongoDB server to effect the new configuration changes. $ sudo systemctl restart mongod You've now successfully installed and secured the MongoDb server. In the next step, you will connect to the server and create a database. 3. Create a MongoDB Database Just like in other SQL database management systems, MongoDB allows you to use the mongosh command-line tool to interact with database objects. This is a standalone package written in Javascript and Node.js. In this step, you'll use the mongosh utility to create a new database. Before you do this, use the following table to familiarize yourself with some MongoDB terms as they compare with the basic SQL concepts to avoid confusion as you continue testing the rest of the guide. MySQL has Database, Table, Column, and Record. MongoDB entities are: Database, Collection, Field, and Document. Once you've grasped the concept of the terms used in MongoDB to name database objects, connect to your MongoDB instance by establishing a new mongosh session by executing the following command. The mongo_db_admin is the superuser/root account that you created earlier. $ mongosh -u mongo_db_admin -p --authenticationDatabase admin Enter the mongo_db_admin password and press ENTER to continue. By default, the mongosh shell should display the following output meaning you're connected to a test database. You should no longer receive the startup authorization warnings since you're now properly authenticated into the database server. test> Create a new e_commerce database. Please note MongoDB does not support the CREATE DATABASE command. Instead, to set up a new database, simply switch the context to an empty database by executing the use command. To create the e_commerce database, run the following command. test> use e_commerce Confirm the response below to make sure you've created and switched to the new database. switched to db e_commerce e_commerce> Please note how the mongosh prompt changes from test> to e_commerce>. In other words, MongoDB prefixes the prompt with the name of your current database. This is very important, especially when you're executing dangerous commands, since you can verify your selected database. In the next step, you'll create a new MongoDB collection and learn how to insert JSON documents into it. 4. Create a Collection and Insert Documents in MongoDB MongoDB handles multiple documents(records) by merging them into a single collection(A replica of a table in SQL). In this step, you'll insert both single and multiple documents in a new collection. Start by inserting a single document(record) into a new products collection using the db.EXAMPLE_COLLECTION.insertOne function as shown below. e_commerce> db.products.insertOne( {"product_id" : 1, "product_name" : "VPS HOSTING", "retail_price" : 5.36 } ) You should get the following acknowledgment. You've now inserted a document into the products collection and received a new unique identifier (insertedId). In this case, the value of the key is 612dd87d5607a039586f5da9. { acknowledged: true, insertedId: ObjectId("612dd87d5607a039586f5da9") } For the basis of better understanding, the above command is equivalent to the following SQL statement. mysql> CREATE TABLE products( product_id INT, product_name VARCHAR(50), retail_price DOUBLE ); INSERT INTO products (product_id, product_name, retail_price) VALUES (1, 'VPS HOSTING', 5.36); In MongoDB, you can insert multiple documents in the same collection by using the insertMany statement and wrapping the documents in a JSON array [...]. For instance, to insert 3 additional records into the products collection, run the following command. e_commerce> db.products.insertMany([ {"product_id" : 2, "product_name" : "DEDICATED CLOUD", "retail_price" : 60.35 }, {"product_id" : 3, "product_name" : "MANAGED DATABASES", "retail_price" : 10.20 }, {"product_id" : 4, "product_name" : "BARE METAL HOSTING", "retail_price" : 120.0 } ]); Confirm the output below, which acknowledges that you've inserted all 3 documents successfully. { acknowledged: true, insertedIds: { '0': ObjectId("612dd95f5607a039586f5daa"), '1': ObjectId("612dd95f5607a039586f5dab"), '2': ObjectId("612dd95f5607a039586f5dac") } } Once a collection and some documents are in place, you'll now locate documents using some search patterns in the next step. 5. Find Documents in a MongoDB Collection If you have a huge list of documents, for instance, thousands or millions of records in a single MongoDB collection, locating a single record manually can be a tedious task. Luckily, MongoDB offers a very important function for finding documents. For instance, to list all the documents from the products collection, execute the following db.EXAMPLE_COLLECTION.find() command. e_commerce> db.products.find() You should now see a list of all documents and products' information as shown below. [ { _id: ObjectId("612dd87d5607a039586f5da9"), product_id: 1, product_name: 'VPS HOSTING', retail_price: 5.36 }, { _id: ObjectId("612dd95f5607a039586f5daa"), product_id: 2, product_name: 'DEDICATED CLOUD', retail_price: 60.35 }, { _id: ObjectId("612dd95f5607a039586f5dab"), product_id: 3, product_name: 'MANAGED DATABASES', retail_price: 10.2 }, { _id: ObjectId("612dd95f5607a039586f5dac"), product_id: 4, product_name: 'BARE METAL HOSTING', retail_price: 120 } ] The db.products.find() command is the equivalent of SELECT * FROM products statement in SQL. Also, when returning records to a client application from the MongoDB database, you can choose to only return a subset of data by using the MongoDB limit() clause. For instance, to return only 2 records from the products collection, run the following command. e_commerce> db.products.find().limit(2) Output. [ { _id: ObjectId("612dd87d5607a039586f5da9"), product_id: 1, product_name: 'VPS HOSTING', retail_price: 5.36 }, { _id: ObjectId("612dd95f5607a039586f5daa"), product_id: 2, product_name: 'DEDICATED CLOUD', retail_price: 60.35 } ] To find a single document, enclose a filter parameter inside the find() function. For instance, to filter products using the product_id field, run the command below. e_commerce> db.products.find({"product_id":2}) The above command displays a single document with a product_id of 2. [ { _id: ObjectId("612dd95f5607a039586f5daa"), product_id: 2, product_name: 'DEDICATED CLOUD', retail_price: 60.35 } ] The db.products.find({"product_id":2}) is the same as SELECT * FROM products where product_id = '2' statement in SQL. Also, you can filter products using the product_name field by executing the following command. e_commerce> db.products.find({"product_name":"MANAGED DATABASES"}) Output. [ { _id: ObjectId("612dd95f5607a039586f5dab"), product_id: 3, product_name: 'MANAGED DATABASES', retail_price: 10.2 } ] You've now searched documents using some filters. Next, you'll update a record that matches a certain filter condition. 6. Update Existing Document in a MongoDB Collection In a production environment, you'll encounter scenarios where you need to update existing MongoDB documents. To make changes to a single record, use the update and $set: {...} statements. For instance, run the command below to change the name of the {"product_id": 2, product_name: "DEDICATED CLOUD" product to SINGLE TENANT PRIVATE CLOUD. e_commerce> db.products.update( { "product_id" : 2 }, { $set: { "product_name" : "SINGLE TENANT PRIVATE CLOUD" } } ) Output: { acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 } The above command is equivalent to UPDATE products SET product_name = 'SINGLE TENANT PRIVATE CLOUD' WHERE product_id = '2'; statement in SQL. When updating records, use a field that is part of a unique index. Confirm the product changes by searching the product details in the collection. e_commerce> db.products.find({"product_id":2}) You've now updated the product's details, as shown below. [ { _id: ObjectId("612de1435607a039586f5dae"), product_id: 2, product_name: 'SINGLE TENANT PRIVATE CLOUD', retail_price: 60.35 } ] Apart from the $set: {...} statement, which completely replaces the value of a field, you can use the $inc: {...} statement to increment a field by a specific value. For instance, to effect a price change of $40 to the SINGLE TENANT PRIVATE CLOUD item with a product_id of 2, run the command below. e_commerce> db.products.update( { "product_id" : 2 }, { $inc: { retail_price: +40 } } ) Make sure you get the following acknowledgment. { acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 } Find the product again from the collection to confirm the new price change. e_commerce> db.products.find({"product_id":2}) As you can confirm from the following output, you've successfully changed the retail_price to $100.35. [ { _id: ObjectId("612de1435607a039586f5dae"), product_id: 2, product_name: 'SINGLE TENANT PRIVATE CLOUD', retail_price: 100.35 } ] Apart from updating records, as you've seen above, you may delete a single document, empty an entire collection, or even delete the database in MongoDB, as you'll see next. 7. Delete a MongoDB Document, Collection, or a Database In MongoDB, you can use the db.EXAMPLE_COLLECTION.deleteOne statement to remove a single document from a collection. This is useful in cases where you no longer want the record to appear in a collection. For instance, when you discontinue a product from your catalog. To delete the {product_id: 1, product_name: 'VPS HOSTING'} document from the products collection, execute the command below. e_commerce> db.products.deleteOne({"product_id" : 1}); Output. { acknowledged: true, deletedCount: 1 } Also, you can use the deleteMany({}) command to remove all existing documents from a collection. This statement is equivalent to the TRUNCATE command in SQL. To delete all products from your products catalog collection, run the command below. e_commerce> db.products.deleteMany({}); The following output verifies that you've successfully deleted 3 records from your products collection. { acknowledged: true, deletedCount: 3 } If you now run a find() command against the products collection, you should now get an empty set. e_commerce> db.products.find() Output. ... > use e_commerce To delete an entire database, first execute the use command. > use e_commerce Output 1. already on db e_commerce e_commerce> Output 2. switched to db e_commerce e_commerce> Then, drop the database by executing the dropDatabase() statement. e_commerce> db.dropDatabase() You've now deleted the database, and you should get the following output. { ok: 1, dropped: 'e_commerce' } After executing all CRUD operations and other commands on the database, you can confirm that the MongoDB installation is now working as expected. You can now create more databases or add additional documents depending on the application you want to build using the MongoDB server. Conclusion In this guide, you've installed and configured the MongoDB package on the Ubuntu 20.04 server. You've also set up a new database and created a collection with several documents. Towards the end of the guide, you've performed all CRUD operations on the MongoDB collection. Use the knowledge in this guide to set up and secure your MongoDB server next time when working on your project.

Was this answer helpful?
Back

Powered by WHMCompleteSolution