MongoDB tutorial: installation and setup

The different database models – SQL and NoSQL – vary a fair bit when it comes to configuration and usage. But open source software MongoDB proves that using a NoSQL solution doesn’t have to mean throwing away years of expertise collected about relational database systems. Admittedly, this document-orientated database with flexible data storage is quite a different idea to classics like MySQL, but there are many similarities too, which you can read about in our introduction to MongoDB. Although the query language and command syntax of MongoDB require a bit of time for familiarisation, SQL experts shouldn’t have many problems getting to grips with the differences.

In the following MongoDB tutorial, we’ll take a closer look at the installation, configuration, and management of this modern database system. We will be using Ubuntu as our operating system in this example.

Step 1: installation

You can find the free open source edition ‘Community Server’ as well as the commercial enterprise solution available on the download center of the official MongoDB website. The first step is to find the right installation file (binary) for your system and to download it. Since MongoDB is available across a selection of platforms, there are a number of different variants for Windows and Linux as well as for OS X and Solaris.

If you’re using a Windows operating system, the database is simply installed into your folder of choice with help from the downloaded file. Windows 10 users can use the Windows Server 2008 (64-bit) version. Users of Linux and co. will have to download an archive file, unzip it and then install it with the help of the package manager. Depending on your distribution, you may first need to import the MongoDB Public GPG Key. For Ubuntu, this authentication key is required, which means you have to implement the following command:

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

Then you should update the list of the package manager:

sudo apt-get update

… and install MongoDB with useful management tools included:

sudo apt-get install -y mongodb-org

Step 2: starting the MongoDB server

You have the option to change the standard installation folder /var/lib/mongodb and the log folder /var/log/mongodb in the configuration file/etc/mongod.conf. The following command will start the database:

sudo service mongod start

If you use the parameter stop instead of the start command, the database will be shut down; the restart command can be used to reboot the database. To test to see whether MongoDB was successfully started, just look up the log file /log/mongodb/mongod.log: The line

[initandlisten] waiting for connections on port <port>

tells you that the database server is running and waiting for incoming connections to the port defined by the configuration file (<port>). The default is port 27017.

Step 3: starting the client

Once the MongoDB server is running, you can start the respective client. We’re using the included command line client Mongo Shell, which is based on JavaScript and may be used for administration of the database as well as accessing and updating the data. You can start the client with a simple terminal command on the same system that the MongoDB application is running:

mongo

The Mongo Shell will automatically connect to the MongoDB server that’s already running on the local host and the port 27017. You can of course always customise these default connection settings with the appropriate parameters as well. These parameters and other important options are listed in the following table:

Parameter

Function description

--shell

Activates the Shell Interface, where you can use the interactive mongo shell after executing a command

--nodb

Disables the connection between the Mongo Shell and a database

--port <port>

Defines the port for the connection

--host <hostname>

Defines the host for a connection

--help or -h

Shows you all possible options

--username <username> or -u <username>

If access rights are defined, you can use this command to log in with your corresponding user name (<username>)

--password <password> or -p <password>

If access rights are defined, you can use this command to enter your corresponding password (<password>)

The brackets included here are not part of the respective parameter and so shouldn’t appear in the final command. For example, when defining port 40000 instead of the standard port 27017 your entry should look like this:

mongo --port 40000

Step 4: creating a database

As soon as MongoDB and the client are running, you can dedicate your time to data management and editing. But first, you should create a database – otherwise your collections and documents will be saved to the automatically generated test database. You can generate a database through the use command. So if you want to create a database with the name mydatabase, for example, then the command will look like this:

use mydatabase

The command use also selects an existing MongoDB database that you want to call up for data processing; by using the short command db you can check which database is currently selected.

Step 5: creating a collection

Your next step is to create your first collection, a binder for various BSON documents in which you will store the data later. The basic syntax follows this pattern:

db.createCollection(<name>, { options } )

The createCollection command contains two parameters: name (title of the collection) and options (optional options to configure in the collection). In the options, you can determine whether the collection should be limited in size (capped: true), and if so, to what number of bytes (size: <number>) or additionally to what number of documents (max: <number>), for example.

A collection with the name mycollection, a byte limit of 6,142,800 and a maximum of 10,000 documents permitted could be created using the following command (the whitespace is simply for clarity):

db.createCollection ("mycollection", { capped: true,
          size: 6142800,
          max: 10000 } )

Step 6: add documents to a collection

After the binder has been created you can populate your collection with documents. There are three different means of doing this:

  • .insertOne()

  • .insertMany()

  • .insert()

The commands above allow you to insert either one document (.insertOne), several documents at once (.insertMany), or simply to insert as many as you list (.insert). The following example shows a simple database entry, containing three pieces of information: name, age, and sex. This document will be stored in the mycollection binder that we created in step 5:

db.mycollection.insertOne(
{
    Name: "Name",
    Age: 28,
    Sex: "female"
  }
)

MongoDB automatically generates a unique ID for this entry and every subsequent entry in this corresponding collection.

Step 7: manage documents

The final step of our MongoDB tutorial concerns the basic management of these created documents. Before you can make changes to a document, you have to call it up first. This action can be performed with the find command and can be expanded with the optional parameters query filter and projection (specification of the displayed result). So to call up the document from the previous step, we’d need the following command:

db.mycollection.find( { Name: "Name", Age: 28 } )

If you want to update this document, you’ll need to perform the update function. Here, you have to define the value you wish to change, choose an update operator, and then enter the new value. So if you want to change the age field in our example, you need the operator $set:

db.mycollection.update( 
{ Age: 28 },
{
  $set: { Age: 30 }
}
)

The other update operators can be found here.

To delete a document from a collection, you’ll need to use the remove command:

db.mycollection.remove()

You can also remove individual documents from the collection by defining criteria like the ID or exact values, thus signalising which database entries are in question to MongoDB. The more specific you are, the more exact the removal process by the database system can be. The command

db.mycollection.remove( { Age: 28 } )

will remove all entries for the value 28 in the Age field. But you can also specify further, telling the database to only remove the first entry that meets this description. This involves using what’s known as a justOne parameter (1):

db.mycollection.remove( { Age: 28 }, 1 )

Further information on user administration, security settings, creation of replicas, or the sharing of data across several systems can be found in the official documentation on the mongodb.com website as well as through the more detailed MongoDB tutorial on tutorialspoint.com.


Wait! We’ve got something for you!
Get your .co.uk domain now, the first year is free.

Enter the web address of your choice in the search bar to check its availability.
12 month for £0/year
then £10/year