MongoDB is a free, flexible and opensource NoSQL database, different from the regular SQL databases like PostgreSQL and MySQL. In MongoDB, data is stored in JSON format and does not require a schema.
At the time of penning down this guide, the latest version of MongoDB was version 4.0. Before proceeding with the installation process, confirm the latest release here.
Using your favorite text editor, create a new YUM repository called mongodb-org.repo
$ vim /etc/yum.repos.d/mongodb-org.repo
Next, add the following content.
[mongodb-org-4.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc
With the MongoDB repository enabled, install MongoDB using the command below.
$ sudo yum install mongodb-org
When prompted to import the MongoDB GPG key, type y and press ENTER.
As part of the Mongo-org package, the following packages will also be installed.
mongodb-org-server – This is the mongod daemon, plus corresponding init scripts and configurations.
mongodb-org-mongos – This is the mongos daemon.
mongodb-org-shell – This is the mongo shell, which is an interactive JavaScript interface to MongoDB, used to perform administrative tasks through the command line.
mongodb-org-tools – This package contains several MongoDB tools used for importing and exporting data, statistics, as well as other utilities.
With MongoDB successfully installed, start the MongoDB daemon using the command as shown.
$ sudo systemctl start mongod
You can also enable it to start on boot by running the following command.
$ sudo systemctl enable mongod
To confirm that MongoDB daemon is running, execute:
$ sudo systemctl status mongod
For best practices, it’s recommended to have authentication to access the database server, because as it stands, any user can have access to it.
To achieve this, open the /etc/mongod.conf file and uncomment the following lines.
security: authorization: enabled
To connect to the MongoDB database run the mongo command below.
$ mongo
To connect to the admin database, run:
use admin
Sample Output
To create a new user called mongoAdmin with the userAdminAnyDatabase role run:
db.createUser(
{
user: "mongoAdmin",
pwd: "changeMe",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Sample Output
Successfully added user: {
"user" : "mongoAdmin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
To exit from the Mongo shell run:
quit()
To login using the admin user account we just created, run:
$ mongo -u mongoAdmin -p --authenticationDatabase admin
Provide the password and later, you will drop to the Mongo shell.
To display users created in the system, run the command below to switch to the admin user.
use admin
Then run the following command.
show users
Wonderful! We have successfully installed MongoDB on CentOS and created an Admin user for authentication.