The different database models – SQL and NoSQL – vary a fair bit when it comes to con­fig­ur­a­tion 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 re­la­tion­al database systems. Ad­mit­tedly, this document-ori­ent­ated database with flexible data storage is quite a different idea to classics like MySQL, but there are many sim­il­ar­it­ies too, which you can read about in our in­tro­duc­tion to MongoDB. Although the query language and command syntax of MongoDB require a bit of time for fa­mil­i­ar­isa­tion, SQL experts shouldn’t have many problems getting to grips with the dif­fer­ences.

In the following MongoDB tutorial, we’ll take a closer look at the in­stall­a­tion, con­fig­ur­a­tion, and man­age­ment of this modern database system. We will be using Ubuntu as our operating system in this example.

Step 1: in­stall­a­tion

You can find the free open source edition ‘Community Server’ as well as the com­mer­cial en­ter­prise solution available on the download center of the official MongoDB website. The first step is to find the right in­stall­a­tion 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 down­loaded 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 dis­tri­bu­tion, you may first need to import the MongoDB Public GPG Key. For Ubuntu, this au­then­tic­a­tion 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 man­age­ment tools included:

sudo apt-get install -y mongodb-org

Step 2: starting the MongoDB server

You have the option to change the standard in­stall­a­tion folder /var/lib/mongodb and the log folder /var/log/mongodb in the con­fig­ur­a­tion 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 suc­cess­fully 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 con­nec­tions to the port defined by the con­fig­ur­a­tion file (<port>). The default is port 27017.

Step 3: starting the client

Once the MongoDB server is running, you can start the re­spect­ive client. We’re using the included command line client Mongo Shell, which is based on JavaS­cript and may be used for ad­min­is­tra­tion 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 ap­plic­a­tion is running:

mongo

The Mongo Shell will auto­mat­ic­ally 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 con­nec­tion settings with the ap­pro­pri­ate para­met­ers as well. These para­met­ers and other important options are listed in the following table:

Parameter Function de­scrip­tion
--shell Activates the Shell Interface, where you can use the in­ter­act­ive mongo shell after executing a command
--nodb Disables the con­nec­tion between the Mongo Shell and a database
--port <port> Defines the port for the con­nec­tion
--host <hostname> Defines the host for a con­nec­tion
--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 cor­res­pond­ing user name (<username>)
--password <password> or -p <password> If access rights are defined, you can use this command to enter your cor­res­pond­ing password (<password>)

The brackets included here are not part of the re­spect­ive 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
Tip: Managed MongoDB from IONOS

Managed MongoDB from IONOS enables you to con­cen­trate on the es­sen­tials. From in­stall­a­tion to operation and main­ten­ance work, IONOS makes sure you always get the best per­form­ance from your data banks.

Step 4: creating a database

As soon as MongoDB and the client are running, you can dedicate your time to data man­age­ment and editing. But first, you should create a database – otherwise your col­lec­tions and documents will be saved to the auto­mat­ic­ally generated test database. You can generate a database through the use command. So if you want to create a database with the name mydata­base, 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 pro­cessing; by using the short command db you can check which database is currently selected.

Step 5: creating a col­lec­tion

Your next step is to create your first col­lec­tion, 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 cre­ate­Col­lec­tion command contains two para­met­ers: name (title of the col­lec­tion) and options (optional options to configure in the col­lec­tion). In the options, you can determine whether the col­lec­tion should be limited in size (capped: true), and if so, to what number of bytes (size: <number>) or ad­di­tion­ally to what number of documents (max: <number>), for example.

A col­lec­tion with the name mycol­lec­tion, 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 col­lec­tion

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

  • .insertOne()

  • .in­sert­Many()

  • .insert()

The commands above allow you to insert either one document (.insertOne), several documents at once (.in­sert­Many), or simply to insert as many as you list (.insert). The following example shows a simple database entry, con­tain­ing three pieces of in­form­a­tion: name, age, and sex. This document will be stored in the mycol­lec­tion binder that we created in step 5:

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

MongoDB auto­mat­ic­ally generates a unique ID for this entry and every sub­sequent entry in this cor­res­pond­ing col­lec­tion.

Step 7: manage documents

The final step of our MongoDB tutorial concerns the basic man­age­ment 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 para­met­ers query filter and pro­jec­tion (spe­cific­a­tion 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 col­lec­tion, you’ll need to use the remove command:

db.mycollection.remove()

You can also remove in­di­vidu­al documents from the col­lec­tion by defining criteria like the ID or exact values, thus sig­nal­ising 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 de­scrip­tion. This involves using what’s known as a justOne parameter (1):

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

Further in­form­a­tion on user ad­min­is­tra­tion, security settings, creation of replicas, or the sharing of data across several systems can be found in the official doc­u­ment­a­tion on the mongodb.com website as well as through the more detailed MongoDB tutorial on tu­tori­alspoint.com.

Go to Main Menu