Easy EMI Options Available

How To Install MongoDB on CentOS 7

Introduction

MongoDB, classified as a NoSQL database because it does not rely on a traditional table-based relational database structure is a document-oriented database that is free and open-source MongoDB does not require a predefined schema before you add data to a database as it uses JSON-like documents with dynamic schemas. The schema can be altered any time and as many times as possible or necessary to do also not having a new database with an updated schema.

In this guide you will get to know how to install MongoDB Community Edition on a CentOS 7 server.

Adding the MongoDB Repository

The mongodb-org package will not exist within the default repositories for CentOS, but MongoDB balances a dedicated repository, so now you will have to add it to the server.

Then you will have to create a .repo file for yum with the help of the vi editor, the package management utility for CentOS:

$ sudo vi /etc/yum.repos.d/mongodb-org.repo

Now you will have to go to the Install on Red Hat section of MongoDB’s documentation and then you will have to add the repository information for the latest stable release to the file:

/etc/yum.repos.d/mongodb-org.repo
[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc

Now you will have to save and close the file.

Now before you carry on, you must assure that whether the MongoDB repository exists within the yum utility. Then the  repolist command will display a list of enabled repositories:

$ yum repolist
Output
. . .
repo id                          repo name
base/7/x86_64                    CentOS-7 - Base
extras/7/x86_64                  CentOS-7 - Extras
mongodb-org-3.2/7/x86_64         MongoDB Repository
updates/7/x86_64                 CentOS-7 - Updates
. . .

Now you will have to proceed with the installation with the MongoDB Repository well settled.

Installing MongoDB

From the third party repository you can install the mongodb-org package with the help of the yum utility.

$ sudo yum install mongodb-org

There are these two prompts Is this ok [y/N]:.The installation of the MongoDB packages is permitted by the first one and the importation of the GPG key is done by the second one .The publisher of MongoDB signs their software and yum uses a key to confirm the integrity of the downloaded packages. At every prompt, you will have to type Y and then you will have to press the ENTER key.

Then you will have to begin the MongoDB service with the help of systemctl utility:

$ sudo systemctl start mongod

The state of MongoDB service with the reload and stop commands can be altered if you want, which is completely natural.

The mongod process is requested by the reload command which analyses the configuration file, /etc/mongod.conf, and then proceeds applying the changes without a restart option.

$ sudo systemctl reload mongod

Now you will have the stop command which will bring an abrupt stop to all the running mongod processes.

$ sudo systemctl stop mongod

After this the systemctl utility will not give any result after it executes the start command, however you will be able to check whether the service which has started by going through the end mongod.log file with the help of the tail command:

$ sudo tail /var/log/mongodb/mongod.log
Output
. . .
[initandlisten] waiting for connections on port 27017

An output of waiting for a connection confirms that MongoDB has started successfully and we can access the database server with the MongoDB Shell:

$ mongo

Note: You must note that after that you have launched the MongoDB shell you can confront a warning similar to this:

** WARNING: soft rlimits too low. Rlimits set to 4096 processes, 64000 files. Number of processes should be at least 32000 : 0.5 times number of files.

MongoDB can launch extra processes in order to balance its workload, it is a threaded application. For MongoDB in order to be more powerful, the number of methods those are authorized for spinning up must be almost half of the number of files so that it can be opened at any time necessary, is stated by the warning here. However in order to resolve this warning you will have to alter the methods soft limit value by changing the 20-nproc.conf file for mongod:

$ sudo vi /etc/security/limits.d/20-nproc.conf

Now you will have to add the following line by the end of the file:

/etc/security/limits.d/20-nproc.conf
. . .
mongod soft nproc 32000

Now you will have to restart it with the help of systemct1 utility in order to avail the new limit to MongoDB.

$ sudo systemctl restart mongod

The warning will cease to exit later if you connect to the MongoDB shell.

In order to get to know how you will communicate with MongoDB from the shell you will have to review the results of the db.help() method, which will help you with the list of methods and ways for the db object.

$ \db.help()
Output
DB methods:
    db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]
    db.auth(username, password)
    db.cloneDatabase(fromhost)
    db.commandHelp(name) returns the help for the command
    db.copyDatabase(fromdb, todb, fromhost)
    db.createCollection(name, { size : ..., capped : ..., max : ... } )
    db.createUser(userDocument)
    db.currentOp() displays currently executing operations in the db
    db.dropDatabase()
. . .

Now you will have to leave the mongod process which will be running in the background, but now you will have to quit the shell by entering the exit command:

>exit
Output
Bye

Verifying Startup

Without a database, a data-base driven function cannot process properly, so you will have to assure that the MongoDB daemon, mongod, will have to start with the system.

You will have to use the systemctl utility to check its startup status:

$ systemctl is-enabled mongod; echo $?

Now you will get an output of zero which will assure an enabled. But the A one, will confirm a disabled daemon which will not start.

Output
. . .
enabled
0

You will have to use the systemctl utility in the event of a disabled daemon, in order to enable it.

$ sudo systemctl enable mongod

Now you will have a running example of MongoDB which will start following a system reboot automatically.

Importing an Example Dataset (Optional)

MongoDB does not come with the data in its test database, very unlike like other database servers. Just because you do not want to test new software with the help of production data, you will have to download a Since we don’t want to experiment with new software using production data, we will download a illustrative dataset from the Import Example Dataset part of the Getting Started with MongoDB documentation. There will a collection of restaurants in JSON document, that you will have to use for practicing with MongoDB in order to avoid the scenario of creating problems to sensitive data.

You need to begin by moving into a writable directory:

$ cd /tmp

Use the curl command and the link from MongoDB to download the JSON file:

$ curl -LO https://raw.githubusercontent.com/mongodb/docs-assets/primer-dataset/primer-dataset.json

The mongoimport command will insert the data into the test database. The --db flag defines which database to use while the --collection flag specifies where in the database the information will be stored, and the --file flag tells the command which file to perform the import action on:

mongoimport --db test --collection restaurants --file /tmp/primer-dataset.json

The output which you will get, assures the importing of the data from the primer-dataset.json file:

Output
connected to: localhost
imported 25359 documents

With the sample dataset in place, you will have to perform a query against it.

Then you will have to relaunch the MongoDB Shell:

$ mongo

The shell will select the test database by default, here is where you have imported your data.

Now you will have to query the restaurants collection with the  method find() in order to show a list of all the restaurants in the dataset. As because the collection contains over 25,000 entries, you will have to use the optional limit() procedure in order to reduce the output of the query to a particular number. However, the pretty() method, additionally, will make the information more user-friendly with newlines and indentations.

> db.restaurants.find().limit( 1 ).pretty()
Output
{
    "_id" : ObjectId("57e0443b46af7966d1c8fa68"),
    "address" : {
        "building" : "1007",
        "coord" : [
            -73.856077,
            40.848447
        ],
        "street" : "Morris Park Ave",
        "zipcode" : "10462"
    },
    "borough" : "Bronx",
    "cuisine" : "Bakery",
    "grades" : [
        {
            "date" : ISODate("2014-03-03T00:00:00Z"),
            "grade" : "A",
            "score" : 2
        },
        {
            "date" : ISODate("2013-09-11T00:00:00Z"),
            "grade" : "A",
            "score" : 6
        },
        {
            "date" : ISODate("2013-01-24T00:00:00Z"),
            "grade" : "A",
            "score" : 10
        },
        {
            "date" : ISODate("2011-11-23T00:00:00Z"),
            "grade" : "A",
            "score" : 9
        },
        {
            "date" : ISODate("2011-03-10T00:00:00Z"),
            "grade" : "B",
            "score" : 14
        }
    ],
    "name" : "Morris Park Bake Shop",
    "restaurant_id" : "30075445"
}

Now you can go forward with the sample datasetin order to accustom yourself with MongoDB or you will have to delete it with the db.restaurants.drop() method:

> db.restaurants.drop()

Now finally you will have to quit the shell by entering exit command:

> exit
Output
Bye

Conclusion

So hereafter from this blog you get to know how to add a third-party repository to yum, also you got to know about the installing of the MongoDB on FreeBSD 10.1 database server, also the way of importing a illustrative dataset, and then how to perform a simple query. You now know how to create your own database with the help of various collections and how to fill them with different documents and start creating a scalable and robust application.

Also Read,

Ayan Sarkar

Ayan Sarkar is one of the youngest entrepreneurs of India. Possessing the talent of creative designing and development, Ayan is also interested in innovative technologies and believes in compiling them together to build unique digital solutions. He has worked as a consultant for various companies and has proved to be a value-added asset for each of them. With years of experience in web development, product managing and building domains for customers, he currently holds the position of the CTO in Webskitters Technology Solutions Pvt. Ltd.