Sunday, July 17, 2016

How To Install & Use Mongodb On Ubuntu 14.04 and 16.04 LTS

How To Install & Use Mongodb
Ubuntu 14.04 and 16.04 LTS

Introduction :

MongoDB is a free and open-source cross-platform document-oriented database. Classified as a NoSQL database, MongoDB avoids the traditional table-based relational database structure (RDBMS) in favor of JSON-like documents with dynamic schema s (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. As of July 2015, MongoDB was the fourth most widely mentioned database engine on the web, and the most popular for document stores.

Here, I am going to show you how to install Mongodb on Ubuntu 14.04 and Ubuntu 16.04 and How to use it to perform basic CURD operations..

Features :

Ad hoc queries, Replication, Indexing, Load Balancing, File storage, Aggregation and Server-side JavaScript execution are some of the salient features of MongoDB.

Install MongoDB :

Why, We Don't Use Ubuntu repository For MongoDB Installation :

That it is always recommended to use the packages (.deb) from the officially MongoDB repository and not from Ubuntu repository. Why? With MongoDB Repository we will assure we are up to date.
At the time of writing this, Ubuntu repository only includes version 2.6.10. While the most current version available is 3.2.5. If you want to install MongoDB from Ubuntu repositories .... use following command..
sudo apt-get install mongodb

Method 1:

In this method you have to execute following commands one by one(manually) to install MongoDB.. but method 2 is more easy way to do this... because the second method uses shell script that will do all these installation steps automatically, for you.. .

Note : Getting MongoDB up and running successfully on Ubuntu 16.04 is challenging. Because of lack of support for systemd in MongoDB.
So using method 2 will do all required tweaks/workarounds for you.
So if you ask me ... I will suggest you to use the second method for easy of installation...

Step 1 : Import the public key used by the package management system

The Ubuntu package management tools (i.e. dpkg and apt) ensure package consistency and authenticity by requiring that distributors sign packages with GPG keys. Issue the following command to import theMongoDB public GPG Key:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927

The sample output should be like this..

Executing: /tmp/tmp.O4U6gXwK4V/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 gpg: requesting key EA312927 from hkp server keyserver.ubuntu.com gpg: key EA312927: public key "MongoDB 3.2 Release Signing Key " imported gpg: Total number processed: 1 gpg: imported: 1 (RSA: 1)

Step 2 : Create a list file for MongoDB & Update The Source List

Next, you will need to add the MongoDB repository details so apt will know where to download the packages from.. . After adding the repository details, you will need to update the packages list.

echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list && sudo apt-get update

Step 3 : Install the MongoDB packages

You can install the latest stable version of MongoDB with following command...

sudo apt-get install -y --allow-unauthenticated mongodb-org
The above command will install MongoDB from official MongoDB repos... contains following packages..
  • mongodb-org : A metapackage that will automatically install the four component packages listed below.
  • mongodb-org-server : Contains the mongod daemon and associated configuration and init scripts.
  • mongodb-org-mongos : Contains the mongos daemon.
  • mongodb-org-shell : Contains the mongo shell.
  • mongodb-org-tools : Contains the following MongoDB tools: mongoimport bsondump, mongodump, mongoexport, mongofiles, mongooplog, mongoperf, mongorestore, mongostat, and mongotop.

Important !

After successfully installing MongoDB, Create Directory named db inside another directory named data (at systems Root directory) and give enough permissions to it... where MongoDB stores the database.. (Otherwise you may encounter 'failed to start' error while starting MongoDB server..). Run following command to create required directory.
sudo mkdir -p /data/db/ && sudo chmod -R 775 /data/

Step 4 :Start MongoDB

Issue the following command to start mongod (mongodb server)

For Ubuntu 14.04 LTS

sudo service mongod start

If mongod starts successfully, you will get output like this...

shivaraj@shivaraj-A14RM0E:~$ sudo service mongod start mongod start/running, process 4518 shivaraj@shivaraj-A14RM0E:~$

For Ubuntu 16.04 LTS

In order to properly launch MongoDB as a service on Ubuntu 16.04, we need to create a unit file which determines how to start or stop the service.

Create a configuration file named mongodb.service to setup unit file as shown below..

sudo touch /etc/systemd/system/mongodb.service

Now open it with your favorite text editor.. (following command will open mongodb.service file with gedit text editor.. you can use your preferred text editor)

sudo gedit /etc/systemd/system/mongodb.service

Now, Paste the following in it..

[Unit] Description=High-performance, schema-free document-oriented database After=network.target [Service] User=mongodb ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf [Install] WantedBy=multi-user.target

Once you have finishes, you can start the mongo server with following command on Ubuntu 16.04.

sudo systemctl start mongodb

You can also check that the service has started properly, run the following command:

sudo systemctl status mongodb

You should see the following output:

⚫ mongodb.service - High-performance, schema-free document-oriented database Loaded: loaded (/etc/systemd/system/mongodb.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2016-07-13 12:56:59 IST; 2h 48min ago Main PID: 947 (mongod) CGroup: /system.slice/mongodb.service └─947 /usr/bin/mongod --quiet --config /etc/mongod.conf Jul 13 12:56:59 shivaraj-A14RM0E systemd[1]: Started High-performance, schema-free document-oriented database.
If you want to enable the MongoDB service that start automatically, when system starts. You can do this by running the following command (For Ubuntu 16.04); sudo systemctl enable mongodb See How To Enable Disable Services On Linux

Method 2:

In this method, the following command will download shell script from GitHub repo and will execute it to make installation of MongoDB easy.. The downloaded script will take care of all things..

wget -O - https://raw.githubusercontent.com/shivarajnaidu/UV-Shell-Scripts/master/MongoDB%20Installation%20Scripts/mongodb-installation-script-for-ubuntu.sh | bash -

Basic Use MongoDB (On Ubuntu)..

Run the mongo command to invoke MongoDB Shell:


You should get output like the one shown below..

shivaraj@shivaraj-A14RM0E:~$ mongo MongoDB shell version: 3.2.8 connecting to: test Server has startup warnings: 2016-07-13T16:08:29.041+0530 I CONTROL [initandlisten] 2016-07-13T16:08:29.041+0530 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. 2016-07-13T16:08:29.041+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2016-07-13T16:08:29.041+0530 I CONTROL [initandlisten] 2016-07-13T16:08:29.041+0530 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. 2016-07-13T16:08:29.041+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2016-07-13T16:08:29.041+0530 I CONTROL [initandlisten] >

Run help command in mongodb shell, you will get sample output like this..

> help db.help() help on db methods db.mycoll.help() help on collection methods sh.help() sharding helpers rs.help() replica set helpers help admin administrative help help connect connecting to a db help help keys key shortcuts help misc misc things to know help mr mapreduce show dbs show database names show collections show collections in current database show users show users in current database show profile show most recent system.profile entries with time >= 1ms show logs show the accessible logger names show log [name] prints out the last segment of log in memory, 'global' is default use set current database db.foo.find() list objects in collection foo db.foo.find( { a : 1 } ) list objects in foo where a == 1 it result of the last line evaluated; use to further iterate DBQuery.shellBatchSize = x set default number of items to display on shell exit quit the mongo shell >

Create or Switch to particular Database :

In mongodb we use keyword use to create new database or to switch to one already exist..

syntax :

use name_of_the_database

For example following will create database named uvdb.. if it's already exists following will switch to that specified database..

use uvdb

To check your currently selected database use the command db.

> use uvdb switched to db uvdb > db uvdb >

Insert a Document

Insert a document into a collection named myfriends. The operation will insert document into collection named myfriends, if one exist already.. Otherwise it will create new collection with specified name and then insert the document..

Syntax :

db.collection.insert() inserts a single document or multiple documents into a collection. To insert a single document, pass a document (JSON like object) to the method; to insert multiple documents, pass an array of documents (array of objects) to the method.

To Insert Single Document into Collection

To insert single document into collection named myfriends .. pass a single object to insert method..

db.myfriends.insert( { "name" : "balu", "address" : { "street" : "Ramar Street", "village" : "Sri Rama Kuppam", "post" : "seethanjeri", "pincode" : "602026", "taluk" : "Uthukkottai", "nation" : "India" }, "education":"computer engineering", "occupation" : "software professional" } )

To Insert Multiple Documents into Collection

To insert multiple documents into collection named myfriends .. pass an array of objects to insert method..

db.myfriends.insert([ { "name" : "balu", "address" : { "street" : "Ramar Street", "village" : "Sri Rama Kuppam", "post" : "seethanjeri", "pincode" : "602026", "taluk" : "Uthukkottai", "nation" : "India" }, "education":"computer engineering", "occupation" : "software professional" }, { "name" : "babu", "address" : { "street" : "Ramar Street", "village" : "Sri Rama Kuppam", "post" : "seethanjeri", "pincode" : "602026", "taluk" : "Uthukkottai", "nation" : "USA" }, "education":"computer engineering", "occupation" : "software professional" } ])

The method returns a WriteResult object with the status of the operation...

If document get successfully inserted into collection you will get output like one shown below.. (here we have inserted 2 doucments so we get "nInserted" : 2).

BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })

Find or Query Data...

You can use the find() method to issue a query to retrieve data from a collection in MongoDB...
Queries can return all documents in a collection or only the documents that match a specified filter or criteria. You can specify the filter or criteria in a document and pass as a parameter to the find() method.
The find() method returns query results in a cursor, which is an iterable object that yields documents.

Query for All Documents in a Collection :

To return all documents in a collection, call the find() method without any arguments. For example, the following operation queries for all documents in the myfriends collection.


You will get out put like this..(The result set contains all documents in the myfriends collection.)

> db.myfriends.find() { "_id" : ObjectId("578795114b9734840360599c"), "name" : "balu", "address" : { "street" : "Ramar Street", "village" : "Sri Rama Kuppam", "post" : "seethanjeri", "pincode" : "602026", "taluk" : "Uthukkottai", "nation" : "India" }, "education" : "computer engineering", "occupation" : "software professional" } { "_id" : ObjectId("578795114b9734840360599d"), "name" : "babu", "address" : { "street" : "Ramar Street", "village" : "Sri Rama Kuppam", "post" : "seethanjeri", "pincode" : "602026", "taluk" : "Uthukkottai", "nation" : "USA" }, "education" : "computer engineering", "occupation" : "software professional" } >

Query data from collection using field names..

You can pass field names as parameters for find method.. so that it will return matched documents..

Syntax :
db.collection.find( { "field": "value" } )
Don't forget to put quotes around fields and value.. when we use dot notation to access an an embedded document(means an property or other object inside an object..) we must use quotes around fields.. otherwise quotes or not mandatory for top level fields like , name field in our example..

For example to find document which consists name field with value balu..




See the above example ... here name is top level field so quotes are optional.. but my suggestion is always use quotes around fields.

The output of the above query is shown below..

> db.myfriends.find({name:"balu"}) { "_id" : ObjectId("578795114b9734840360599c"), "name" : "balu", "address" : { "street" : "Ramar Street", "village" : "Sri Rama Kuppam", "post" : "seethanjeri", "pincode" : "602026", "taluk" : "Uthukkottai", "nation" : "India" }, "education" : "computer engineering", "occupation" : "software professional" } >

Querying data from embedded documents .. means using dot notation needs quotes around field names.... This is mandatory...
See the following example..

We are going to query village embedded inside a address document..

db.myfriends.find({"address.village":"Sri Rama Kuppam"})

Sample output

> db.myfriends.find({"address.village":"Sri Rama Kuppam"}) { "_id" : ObjectId("578795114b9734840360599c"), "name" : "balu", "address" : { "street" : "Ramar Street", "village" : "Sri Rama Kuppam", "post" : "seethanjeri", "pincode" : "602026", "taluk" : "Uthukkottai", "nation" : "India" }, "education" : "computer engineering", "occupation" : "software professional" } { "_id" : ObjectId("578795114b9734840360599d"), "name" : "babu", "address" : { "street" : "Ramar Street", "village" : "Sri Rama Kuppam", "post" : "seethanjeri", "pincode" : "602026", "taluk" : "Uthukkottai", "nation" : "USA" }, "education" : "computer engineering", "occupation" : "software professional" } >

For more query statement usage .. refer Official Documentation..

Updating Data..

Update operations can modify/replace existing documents in a collection. The method accepts following as its parameters:

  • a filter document to match the documents to update
  • an update document to specify the modification to perform
  • an options parameter (optional).

By default, the update() method updates a single document. Use the multi option to update all documents that match the criteria.
You cannot update the _id field.


For example, we are going to update name field which has value "balu" with another value "shyamala".. in our demo database.

db.myfriends.update({"name":"balu"}, {$set: { "name":"Shyamala"}} )

The above will update document with name field value with balu, with the new value shyamala..

To update multiple documents in a collection which matches to match object use multi option..

db.myfriends.update({"name":"balu"}, {$set: { "name":"Shyamala"}}, { multi: true} )
The update operation returns a WriteResult object which contains the status of the operation.
Sample Output..
> db.myfriends.update({"name":"balu"}, ... {$set: { "name":"Shyamala"}}, ... { multi: true} ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) >

Replace a Document
To replace the entire document except for the _id field, pass an entirely new document as the second argument to the update() method. The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable. If you do include the _id field, it must be the same value as the existing value.

db.myfriends.update({"name":"Shyamala"}, { "name" : "yuvaraj", "address" : { "village" : "Sri Rama Kuppam", "state" : "Tamil Nadu", "nation" : "India" } })

Sample Output..
Note that the WriteResult object showing status of operation..

> db.myfriends.update({"name":"Shyamala"}, ... { ... "name" : "yuvaraj", ... "address" : { ... "village" : "Sri Rama Kuppam", ... "state" : "Tamil Nadu", ... "nation" : "India" ... } ... }) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) >

Now , if you check the database .. it will looks like below one..

> db.myfriends.find({"address.village":"Sri Rama Kuppam"}) { "_id" : ObjectId("578795114b9734840360599c"), "name" : "yuvaraj", "address" : { "village" : "Sri Rama Kuppam", "state" : "Tamil Nadu", "nation" : "India" } } { "_id" : ObjectId("578795114b9734840360599d"), "name" : "babu", "address" : { "street" : "Ramar Street", "village" : "Sri Rama Kuppam", "post" : "seethanjeri", "pincode" : "602026", "taluk" : "Uthukkottai", "nation" : "USA" }, "education" : "computer engineering", "occupation" : "software professional" } >

Here you can find more about UPDATE method..

Removing Data..

We can easily remove data with remove() method.. This method takes query statement like parameters to determines the documents to remove.

Syntax :

Remove All Documents That Match a with condition..

Sample OutPut:
> db.myfriends.remove({"name":"yuvaraj"}) WriteResult({ "nRemoved" : 1 })

To Remove All Documents in the collection....

db.collection.remove( { } )

For example to remove all documents in our demo database collection named "myfriends.."

db.myfriends.remove( { } )

Drop a Collection
To drop a whole collection.. use drop method..


For our case..


Upon successful drop of the collection, the operation returns true.


If the collection to drop does not exist, the operation will return false.

> db.myfriends.drop() true >

For More information about remove method and drop method .. see Official documentation for remove and drop methods..

SQL to MongoDB..

Here you can find SQL to MongoDB mapping guide....

Hi friends, If you found any issue or typo error, please feel free to report it.. You can either open an issue on github or you can also report it on our Facebook Page via message(www.fb.com/opensourceinside) .