How To Install & Use Mongodb
On
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.. ☻ .
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..
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
- 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...
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:
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:
mongo
You should get output like the one shown below..
Run help command in mongodb shell, you will get sample output like this..
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.
db
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()
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).
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.
db.myfriends.find()
You will get out put like this..(The result set contains all documents in the myfriends collection.)
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" } )
For example to find document which consists name field with value balu..
db.myfriends.find({name:"balu"})
or
db.myfriends.find({"name":"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..
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
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.
db.collection.update(parameters....)
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}
)
Sample Output..
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..
Now , if you check the database .. it will looks like below one..
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 :
db.collection.remove(parameters...)
Remove All Documents That Match a with condition..
db.myfriends.remove({"name":"yuvaraj"})
Sample OutPut:
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..
db.collection.drop()
For our case..
db.myfriends.drop()
Upon successful drop of the collection, the operation returns true.
true
If the collection to drop does not exist, the operation will return false.
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....