Instructions for installing and using MongoDB

Tram Ho

Prologue

Hello everyone, back to the “What I know about MongoDB” series of articles, a series about an extremely popular NoSQL DB, MongoDB.

In the content of this article, I will share how to install mongodb as standalone and some basic operations with mongodb such as creating database, creating collection, adding editing and deleting basic data…

Instructions for installing mongodb

MongoDB can be installed on many platforms, from installing packages on operating systems such as Linux, MacOS, Window.. to installing using docker or installing on Kubernetes via helmcharts.

In this content, I will show you how to install mongodb on Linux and specifically Ubuntu version 20.04. The installation on other OSes is basically not too different, you can refer to it here

image.png

Install mongodb on ubuntu 20.04

I will install MongoDB 6.0 Community Edition on Ubuntu 20.04 LTS Focal. The installation procedure is quite simple, follow the steps below!

Step 1: Add the key for the repo to install mongodb

Return result ” OK ” is success. If there is an error, please perform the following additional steps and then repeat the above step:

Step 2: Add the key for the repo to install mongodb

Step 3: Update the local repo again

Step 4: Install package of mongodb

Once saved when installing with a package on OS, we need to mark this installation package as not automatically updating when updating the repo by the following way:

Launch mongodb

Note about ulimit . configuration

You need to set the ulimit value for max-open-files to at least 64000 otherwise the mongod service will give an error. The ulimit value is set for each user of the OS, so it needs to be set correctly for the user used to run mongodb.

When installing with package manager like using apt on ubuntu above, the ulimit value has been set automatically, you can verify it again as follows:

Step 1: Check the PID of mongod

Step 2: Check the ulimit values ​​of the above process (in this case PID=475)

You will see that the value of the parameter ” Max open files ” is being set to 64000.

Configuration of service mongod

When installing the mongodb-org package, the default mongod service is created and defined by the service configuration file at /lib/systemd/system/mongod.service .

In this config file contains the parameters to run this service, in which the important parameter is ExecStart :

And you can see that the main config file to run this service is /etc/mongod.conf . You can completely customize the path to the service’s config file, as well as customize the parameters in this config file:

Some important configuration parameters to note:

  • storage : Path to the directory containing the data of mongodb
  • systemLog : Path to the directory containing the log of this mongod service
  • net : Declare the Port and IP to bindport. Default will only bind Port (default 27017) to localhost (127.0.0.1) so standing from another host will not be able to connect to the db if you do not bind to other interfaces of the host.

Run mongodb

After checking and customizing the configuration parameters (if desired), we can start mongodb. If you have edited the service configuration file, you need to reload it with the command:

Then start mongodb:

The result when mongod starts successfully is as follows:

Start using mongodb

Now that mongodb has been started, you can start connecting to the db by running the mongosh command on the server you are installing mongodb on.

So we have connected to mongodb and by default will connect to the database named test .

Basic operations with mongodb

First of all, it should be recalled that some concepts on mongodb will be different from those in other Rational Databases such as:

So here we need to remember the organization in mongodb will be: database => collection => document => field.

Create new database in mongodb with mongosh

When I first connect to mongodb, I am connected to a white db called test . To see the list of databases available in the system, use the command:

Note that the test db is a blank db so it will not be listed in the show dbs statement.

To create a new DB, execute the command use [database-name] :

Thus, a blank DB named demo is created and we will also be automatically transferred to that demo DB. In the command prompt will tell us which database we are working on

Create new collection in database

There are 2 ways to create collections in mongodb:

  • Create with createCollection . command
  • Created by inserting data into the collection (collection will be created if it doesn’t already exist)

Create a collection using the createCollection . command

We can create a new Collection named staff as follows:

Create a collection with the insertOne command

Insert into collection

To add a document to the collection, use the insertOne command

To add multiple documents to the collection, use the insertMany command:

Result:

Query data in the collection (find function)

There are 2 ways to use find in mongodb: find() and findOne()

Using find()

To select data from mongodb collection, we can use find() function. This function can take as input a query object to filter data. If this filter condition is empty, all documents of this collection will be returned.

Example select all from the staff collection:

Using findOne()

Use the findOne() function to select only one document. This function also accepts the query condition as an object and if left blank it will return the first document it finds.

Filter the data

We can filter data by parameters, for example filter which staff is name (condition is "gender": "male" ):

Filter field to get results by projection

We can filter out the required fields using the 2nd parameter in the find() function called projection . For example, we only want to get the name and cert information of male staff:

This way can filter out unwanted fields, but the ” _id ” field, if you want to hide it, you have to set it to zero in the projection configuration:

Update data in collection

To update data in the collection we can use updateOne() or updateMany() function. These functions take as the first parameter a query condition to choose which documents to update.

And the th parameter is an object that defines the data to be updated.

updateOne() function

The updateOne() function updates the first document that satisfies the query condition. For example, we need to update the age of male employees to 20:

Check data before updating:

Perform update

**After updating, only the first record found has been updated

updateMany() function

This function will update all documents that satisfy the query condition. For example, we update all male employees to 25 years old:

After updating, all records that satisfy the search criteria have been updated

Delete data in the collection

Similar to the insert or update command, mongodb also has two delete functions, deleteOne() and deleteMany() . And still with the same idea, deleteOne() will delete the first document that meets the filter condition and deleteMany() will delete all documents that satisfy the filter condition.

Example delete female employee:

Remove all male employees:

Some operations with db and collection

List the collection in the db:

Delete a collection:

Delete a database:

Through this article, hopefully, those who are new to mongodb will be able to install a lab system and perform very basic operations with mongodb.

In the next article, I will show you how to install a mongodb sharded cluster with full components to ensure the elements of redundancy, high availability and scalable using sharding and replication.

If you find the article useful, please support by upvote the article to give me more motivation to write!

See you all in the next part!

Share the news now

Source : Viblo