MongoDB Administrator's Guide

4 (1 reviews total)
By Cyrus Dasadia
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Installation and Configuration

About this book

MongoDB is a high-performance and feature-rich NoSQL database that forms the backbone of the systems that power many different organizations. Packed with many features that have become essential for many different types of software professional and incredibly easy to use, this cookbook contains more than 100 recipes to address the everyday challenges of working with MongoDB.

Starting with database configuration, you will understand the indexing aspects of MongoDB. The book also includes practical recipes on how you can optimize your database query performance, perform diagnostics, and query debugging. You will also learn how to implement the core administration tasks required for high-availability and scalability, achieved through replica sets and sharding, respectively. You will also implement server security concepts such as authentication, user management, role-based access models, and TLS configuration. You will also learn how to back up and recover your database efficiently and monitor server performance.

By the end of this book, you will have all the information you need - along with tips, tricks, and best practices - to implement a high-performance MongoDB solution.

Publication date:
October 2017
Publisher
Packt
Pages
226
ISBN
9781787126480

 

Chapter 1. Installation and Configuration

In this chapter, we will cover the following recipes:

  • Installing and starting MongoDB on Linux
  • Installing and starting MongoDB on macOS
  • Binding MongoDB process to a specific network interface and port
  • Enabling SSL for MongoDB
  • Choosing the right MongoDB storage engine
  • Changing storage engine
  • Separating directories per database
  • Customizing the MongoDB configuration file
  • Running MongoDB as a Docker container
 

Introduction


In this chapter, we will look at how to install a standalone MongoDB server. We will also look at how to perform some useful customization to the default configuration of a MongoDB server. Lastly, we will run a MongoDB server inside a Docker container.

Note

MongoDB 3.4 was the latest stable release available while writing this book. All recipes in this and the subsequent chapters assume you are using MongoDB 3.4 or higher.

 

Installing and starting MongoDB on Linux


Getting ready

You will need a machine running Ubuntu 14.04 or higher, although in theory any Red Hat or Debian-based Linux distribution should be fine. You will also need to download the latest stable binary tarball from https://www.mongodb.com/download-center

How to do it…

  1. Create a directory /data and untar your downloaded file into this directory so that you now have a /data/mongodb-linux-x86_64-ubuntu1404-3.4.4 directory. All of MongoDB's core binaries are available in the /data/mongodb-linux-x86_64-ubuntu1404-3.4.4/bin directory.
  2. Create a symbolic link to the versioned file directory for a simpler naming convention and also allowing us to use a generic directory name (for example, in scripts):
ln -s /data/mongodb-linux-x86_64-ubuntu1404-3.4.4/ /data/mongodb
  1. Create a directory for the database:
mkdir /data/db
  1. Start the MongoDB server:
/data/mongodb/bin/mongod --dbpath /data/db
  1. You should see output like this:
2017-05-14T10:07:15.247+0000 I CONTROL  [initandlisten] MongoDB starting : pid=3298 port=27017 dbpath=/data/db 64-bit host=vagrant-ubuntu-trusty-64
 2017-05-14T10:07:15.247+0000 I CONTROL  [initandlisten] db version v3.4.4
 2017-05-14T10:07:15.248+0000 I CONTROL  [initandlisten] git version: 888390515874a9debd1b6c5d36559ca86b44babd
 2017-05-14T10:07:15.248+0000 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1f 6 Jan 2014
 2017-05-14T10:07:15.248+0000 I CONTROL  [initandlisten] allocator: tcmalloc
 2017-05-14T10:07:15.249+0000 I CONTROL  [initandlisten] modules: none
 2017-05-14T10:07:15.249+0000 I CONTROL  [initandlisten] build environment:
 2017-05-14T10:07:15.249+0000 I CONTROL  [initandlisten]     distmod: ubuntu1404
 2017-05-14T10:07:15.249+0000 I CONTROL  [initandlisten]     distarch: x86_64
 2017-05-14T10:07:15.250+0000 I CONTROL  [initandlisten]     target_arch: x86_64
 2017-05-14T10:07:15.250+0000 I CONTROL  [initandlisten] options: { storage: { dbPath: "/data/db" } }
 < -- snip -- >
 2017-05-14T10:07:15.313+0000 I COMMAND  [initandlisten] setting featureCompatibilityVersion to 3.4
 2017-05-14T10:07:15.313+0000 I NETWORK  [thread1] waiting for connections on port 27017
  1. You can stop the server by pressing Ctrl + C.
  2. Additionally, for convenience, we can edit the system's PATH variable to include the mongodb binaries directory. This allows us to invoke the mongodb binaries without having to type the entire path. For example, to execute the mongo client, instead of having to type /data/mongodb/bin/mongo every time, we can simply type mongo. This can be done by appending your ~/.bashrc or ~/.zshrc files for bash and zsh respectively, with the following lines:

PATH=/data/mongodb/bin:${PATH}
export PATH

How it works…

We downloaded a precompiled binary package and started the mongod server using the most basic command line parameter --dbpath so that it uses a customized directory, /data/db for storing databases. As you might have noticed, the MongoDB server by default, starts listening on TCP port 27017 on all interfaces.

There's more…

The mongod binary has a lot of interesting options. You can view the available command line parameters by using --help or -h. Alternatively, you can also find a detailed reference of available options, at https://docs.mongodb.com/master/reference/program/mongod/.

Just like most mature community projects, MongoDB also provides packages for formats supported by Debian/Ubuntu and Red Hat/CentOS package managers. There is extensive documentation on how to configure your operating system's package manager to automatically download the MongoDB package and install it. For more information on how to do so, see: https://docs.mongodb.com/master/administration/install-on-linux/.

 

Installing and starting MongoDB on macOS


Similar to the previous recipe, Installing and starting MongoDB on Linux, we will see how to set up MongoDB on a macOS operating system.

Getting ready

MongoDB supports macOS 10.7 (Lion) or higher, so ensure that your operating system is upgraded. Download the binary files the latest stable binary tarball from https://www.mongodb.com/download-center.

How to do it...

  1. In this recipe, we will be installing MongoDB in the user's home directory. Create a directory ~/data/ and extract the TAR file in this directory:
tar xvf mongodb-osx-x86_64-3.4.4.tgz

All of MongoDB's core binaries are available in the ~/data/mongodb-osx-x86_64-3.4.4/bin directory.

  1. Create a symbolic link to the versioned file directory for simpler naming conventions and also allowing us to use a generic directory name (for example, in scripts):
cd ~/data/
ln -s mongodb-osx-x86_64-3.4.4 mongodb
  1. Create a directory for the database:
mkdir ~/data/db
  1. Start the MongoDB server:
~/data/mongodb/bin/mongod --dbpath ~/data/db
  1. You should see output like this:
2017-05-21T15:21:20.662+0530 I CONTROL  [initandlisten] MongoDB starting : pid=960 port=27017 dbpath=/Users/cyrus.dasadia/data/db 64-bit host=foo
 2017-05-21T15:21:20.662+0530 I CONTROL  [initandlisten] db version v3.4.4
 2017-05-21T15:21:20.662+0530 I CONTROL  [initandlisten] git version: 888390515874a9debd1b6c5d36559ca86b44babd
 2017-05-21T15:21:20.662+0530 I CONTROL  [initandlisten] allocator: system
 2017-05-21T15:21:20.662+0530 I CONTROL  [initandlisten] modules: none
 2017-05-21T15:21:20.662+0530 I CONTROL  [initandlisten] build environment:
 2017-05-21T15:21:20.662+0530 I CONTROL  [initandlisten]     distarch: x86_64
 2017-05-21T15:21:20.662+0530 I CONTROL  [initandlisten]     target_arch: x86_64
 2017-05-21T15:21:20.662+0530 I CONTROL  [initandlisten] options: { storage: { dbPath: "/Users/cyrus.dasadia/data/db" } }
 <<--- snip -- >>
 2017-05-21T15:21:21.492+0530 I NETWORK  [thread1] waiting for connections on port 27017
  1. You can press Ctrl + C to stop the server.

 

  1. Additionally, for convenience, we can edit the system's PATH variable to include the MongoDB binaries directory. This allows us invoke the MongoDB binaries without having to type the entire path. For example, to execute the mongo client, instead of having to type ~/mongodb/bin/mongo every time we can simply type mongo. This can be done by appending your ~/.bashrc or ~/.zshrc files for bash and zsh respectively, with the following lines:
PATH=~/data/mongodb/bin:${PATH}
export PATH

How it works…

Similar to our first recipe, we downloaded a precompiled binary package and started the MongoDB server using the most basic command line parameter --dbpath such that it uses a customized directory ~/data/db for storing databases. As you might have noticed, MongoDB server by default, starts listening on TCP 27017 on all interfaces. We also saw how to add the MongoDB binary directory's path to our system's PATH variable for a more convenient way to access the MongoDB binaries.

 

Binding MongoDB process to a specific network interface and port


As you might have observed, after starting the MongoDB server, the mongod process binds to all interfaces which may not be suitable for all use cases. For example, if you are using MongoDB for development or you are running a single node instance on the same server as your application, you probably do not wish to expose MongoDB to the entire network. You might also have a server with multiple network interfaces and may wish to have MongoDB server listen to a specific network interface. In this recipe, we will see how to start MongoDB on a specific interface and port.

Getting ready

Make sure you have MongoDB installed on your system as shown in the previous recipes.

How to do it...

  1. Find your system's network interfaces and corresponding IP address(s) using the ifconfig command. For example, let's assume your system's IP address is 192.168.1.112.
  2. Start the mongod daemon without any special flags:
mongod --dbpath /data/db

This starts the mongod daemon which binds to all network interfaces on port 27017.

  1. In a separate Terminal, connect to your MongoDB server on this IP:
mongo 192.168.1.112:27017

You should see a MongoDB shell.

  1. Now stop the previously running mongod daemon (press Ctrl + C in the Terminal) and start the daemon to listen to your loopback interface:
mongod --dbpath /data/db --bind_ip 127.0.0.1
  1. In a separate Terminal, connect to your MongoDB server on this IP:
mongo 192.168.1.112:27017
  1. This time the mongo client will exit with a connect failed message. Let's connect to your loopback IP and it should work:
mongo 127.0.0.1:27017
  1. Stop the mongod daemon (press Ctrl + C in the Terminal) and let's start the daemon such that it binds to a different port as well:
mongod --dbpath /data/db --bind_ip 127.0.0.1 --port 27000
  1. In a separate Terminal, connect to your MongoDB server on this IP:
mongo 127.0.0.1:27000
  1. You should be connected to the server and see the mongo shell.

How it works...

By default, the mongod daemon binds to all interfaces on TCP port 27017. By passing the IP address with the --bind_ip parameter, we instructed mongod daemon to listen only on this socket. Next we passed the --port parameter along with --bind_ip to instruct the mongod daemon to listen to a particular port and IP. Using a non-standard port is a common practice when one wishes to run multiple instances of mongod daemon (along with a different --dbpath) or wish to add a little touch security by obscurity. Either way, we will be using this practice in our later recipes to test shards and replica sets setups running on a single server.

 

Enabling SSL for MongodDB


By default, connections to MongoDB server are not encrypted. If one were to intercept this traffic, almost all the data transferred between the client and the server is visible as clear text. If you are curious, I would encourage you to use tcpdump or wireshark to capture packets between a mongod daemon and the client. As a result, it is highly advisable to make sure that you encrypt all connections to your mongod set by enabling Transport Layer Security (TLS) also commonly known as SSL.

Getting ready

Make sure you have MongoDB installed on your system as shown in the previous recipes.

Note

The default MongoDB binaries for OS X are not compiled with SSL, you may need to manually recompile the source code or use Homebrew:brew install mongodb --with-openssl.

How to do it..

  1. First, let us generate a self-signed certificate using OpenSSL, in the /data directory:
openssl req -x509 -newkey rsa:4096 -nodes -keyout mongo-secure.key -out mongo-secure.crt -days 365
  1. Combine the key and certificate into a single .pem file:
cat mongo-secure.key mongo-secure.crt > mongo-secure.pem
  1. Start the mongod daemon, with SSL enabled and listening on the default socket that is, localhost 27017:
mongod  --dbpath /data/db  --sslMode requireSSL --sslPEMKeyFile /data/mongo-secure.pem
  1. In another window, connect to this server using a mongo client:
mongo localhost:27017
  1. You should see a connect failed error on the client Terminal. Switch to the server's console window and you should see a log message indicating that the connection was rejected, something like this:
2017-05-13T16:51:08.031+0000 I NETWORK  [thread1] connection accepted from 192.168.200.200:43441 #4 (1 connection now open)
2017-05-13T16:51:08.032+0000 I -        [conn4] AssertionException handling request, closing client connection: 17189 The server is configured to only allow SSL connections
2017-05-13T16:51:08.032+0000 I -        [conn4] end connection 192.168.200.200:43441 (1 connection now open)
  1. Now, switch back to the other console window and connect to the server again but this time using SSL:
mongo --ssl --sslAllowInvalidCertificates
  1. You should be connected to the server and see the mongo shell.

How it works...

In step 1, we created a self-signed certificate to get us started with SSL enabled connections. One could very well use a certificate signed by a valid Certificate Authority (CA), but for test purposes we are good with a self-signed certificate. In all honesty, if connection security is all you need, a self-signed certificate can also be used in a production environment as long as you keep the keys secure. You might as well take it a step forward by creating your own CA certificate and use it to sign your certificates.

In step 2, we concatenate the key and the certificate file. Next, in step 3, we start the mongod daemon with --sslMode requireSSL followed by providing the path to the concatenated .pem file. At this point, we have a standalone MongoDB server listening to the default port 27017, ready to accept only SSL based clients.

Next, we attempt to connect to the mongod server using the default non-SSL mode, which is immediately rejected by the sever. Finally, in step 5 we explicitly make an SSL connection by providing the --ssl parameter followed by --sslAllowInvalidCertificates. The latter parameter is used because we are using a self-signed certificate on the server. If we were using an certificate signed by a authorized CA or even a self-signed CA, we could very well use the --sslCAFile to provide the CA certificate.

There's more…

MongoDB also supports X.509 certificate-based authentication as an option to username and passwords. We will cover this topic in Chapter 9, Authentication and Security in MongoDB.

 

Choosing the right MongoDB storage engine


Starting with MongoDB Version 3.0, a new storage engine named WiredTiger was available and very soon it became the default storage engine in version 3.2. Up until then, MMAPv1 was used as the default storage engine. I will give you a brief rundown on the main features of both storage engines and hopefully it should give you enough to decide which one suits your application's requirements.

WiredTiger

WiredTiger provides the ability, for multiple clients, to perform write operations on the same collection. This is achieved by providing document-level concurrency such that during a given write operation, the database only locks a given document in the collection as against its predecessors, which would lock the entire collection. This drastically improves performance for write heavy applications. Additionally, WiredTiger provides compression of data for indexes and collections. The current compression algorithms used by WiredTiger are Google's Snappy and zLib. Although disabling compression is possible, one should not immediately jump this gun unless it is truly load-tested while planning your storage strategy.

WiredTiger uses Multi-Version Concurrency Control (MVCC) that allows asserting point-in-time snapshots of transactions. These finalized snapshots are written to disk which helps create checkpoints in the database. These checkpoints eventually help determine the last good state of data files and helps in recovery of data during abnormal shutdowns. Additionally, journaling is also supported with WiredTiger where write-ahead transaction logs are maintained. The combination of journaling and checkpoints increases the chance of data recovery during failures. WiredTiger uses internal caching as well as filesystem cache to provide faster responses on queries. With high concurrency in mind, the architecture of WiredTiger is such that it better utilizes multi-core systems.

MMAPv1

MMAPv1 is quite mature and has proven to be quite stable over the years. One of the storage allocation strategies used with this engine is the power of two allocation strategy. This primarily involves storing double the amount of document space (in power of twos) such that in-place updates of documents become highly likely without having to move the documents during updates. Another storage strategy used with this engine is fixed sizing. In this, the documents are padded (for example, with zeros) such that maximum data allocation for each document is attained. This strategy is usually followed by applications that have fewer updates.

Consistency in MMAPv1 is achieved by journaling, where writes are written to a private view in memory which are written to the on-disk journal. Upon which the changes are then written to a shared view that is the data files. There is no support for data compression with MMAPv1. Lastly, MMAPv1 heavily relies on page caches and hence uses up available memory to retain the working dataset in cache thus providing good performance. Although, MongoDB does yield (free up) memory, used for cache, if another process demands it. Some production deployments avoid enabling swap space to ensure these caches are not written to disk which may deteriorate performance.

The verdict

So which storage engine should you choose? Well, with the above mentioned points, I personally feel that you should go with WiredTiger as the document level concurrency itself is a good marker for attaining better performance. However, as all engineering decisions go, one should definitely not shy away from performing appropriate load testing of the application across both storage engines.

Note

The enterprise MongoDB version also provides in-memory storage engine and supports encryption at rest. These are good features to have depending on your application's requirements.

 

Changing storage engine


In this recipe, we will look at how to migrate existing data onto a new storage engine. MongoDB does not allow on the fly (live) migrations, so we will have to do it the hard way.

Getting ready

Ensure you have a MongoDB database installation ready.

How to do it...

  1. Start the mongod daemon to explicitly use MMAPv1 storage engine:
/data/mongodb/bin/mongod --dbpath /data/db --storageEngine mmapv1
  1. Start the mongo client and you should be presented with the MongoDB shell. Execute the following commands in the shell:
> var status = db.serverStatus()
> status['storageEngine']
{
   "name" : "mmapv1",
   "supportsCommittedReads" : false,
   "readOnly" : false,
   "persistent" : true
}
  1. Now let's add some random data into it. Run the following JavaScript code to insert 100 documents with random data:
> use mydb
> for(var x=0; x<100; x++){
  db.mycol.insert({
     age:(Math.round(Math.random()*100)%20)
     })
  }
> db.mycol.count()
100
  1. Exit the shell and perform a full backup using mongodump command:
mkdir /data/backup
mongodump -o /data/backup --host localhost:27017
  1. Now shutdown the mongod process.
  2. Create a new data directory for the migration and start the mongod daemon with a new storage engine:
mkdir /data/newdb
/data/mongodb/bin/mongod --dbpath /data/newdb --storageEngine wiredTiger
  1. Let's restore the previous backup to this new instance:
mongorestore /data/backup/
  1. Start the mongo shell and check your data:
> var status = db.serverStatus()
> status['storageEngine']
{
    "name" : "wiredTiger",
    "supportsCommittedReads" : true,
    "readOnly" : false,
    "persistent" : true
}
> use mydb
switched to db mydb
> db.mycol.count()
100

How it works...

As WiredTiger is the default storage engine for MongoDB 3.2, for this exercise, we explicitly started a MongoDB instance with MMAPv1 storage engine in step 1. In step 2, we stored the db.serverStatus() command's output in a temporary variable to inspect the output of the server's storageEngine key. This helps us see which storage engine our MongoDB instance is running on. In step 3, we switched to database mydb and ran a simple JavaScript function to add 100 documents to a collection called mycol. Next, in step 4, we created a backup directory /data/backup which is passed as a parameter to mongodump utility. We will discuss more about the mongodump utility in Chapter 6, Managing MongoDB Backups.

Once we shutdown the mongod instance, in step 5, we are now ready to start a new instance of MongoDB but this time with WiredTiger storage engine. We follow the basic practice of covering for failure and instead of removing /data/db, we create a new path for this instance (#AlwaysHaveABackupPlan). Our new MongoDB instance is empty, so in step 7 we import the aforementioned backup into the database using the mongorestore utility. As the new MongoDB instance is running WiredTiger storage engine, our backup (which is essentially BSON data) is restored and saved on disk using this storage engine. Lastly, in step 8, we simply inspect the storageEngine key on the db.serverStatus() output and confirm that we are indeed using WiredTiger.

As you can see, this is an overly simplistic example of how to convert MongoDB data from one storage engine format to another. One has to keep in mind that this operation will take a significant amount of time depending on the size of data. However, application downtime can be averted if we were to use a replica set. More on this later.

 

Separating directories per database


In this recipe we will be looking at how to optimize on disk I/O by separating databases in different directories.

Getting ready

Ensure you have a MongoDB database installation ready.

How to do it...

  1. Start mongod daemon with no special parameters:
/data/mongodb/bin/mongod --dbpath /data/db
  1. Connect to mongo shell, create a test db and insert a sample document:
mongo localhost:27017
> use mydb
> db.mycol.insert({foo:1})
  1. Inspect the /data/db directory structure, it should look something like this:
ls /data/db
total 244
drwxr-xr-x  4 root root  4096 May 21 08:45 .
drwxr-xr-x 10 root root  4096 May 21 08:42 ..
-rw-r--r--  1 root root 16384 May 21 08:43 collection-0-626293768203557661.wt
-rw-r--r--  1 root root 16384 May 21 08:43 collection-2-626293768203557661.wt
-rw-r--r--  1 root root 16384 May 21 08:43 collection-5-626293768203557661.wt
drwxr-xr-x  2 root root  4096 May 21 08:45 diagnostic.data
-rw-r--r--  1 root root 16384 May 21 08:43 index-1-626293768203557661.wt
-rw-r--r--  1 root root 16384 May 21 08:43 index-3-626293768203557661.wt
-rw-r--r--  1 root root 16384 May 21 08:43 index-4-626293768203557661.wt
-rw-r--r--  1 root root 16384 May 21 08:43 index-6-626293768203557661.wt
drwxr-xr-x  2 root root  4096 May 21 08:42 journal
-rw-r--r--  1 root root 16384 May 21 08:43 _mdb_catalog.wt
-rw-r--r--  1 root root     6 May 21 08:42 mongod.lock
-rw-r--r--  1 root root 16384 May 21 08:44 sizeStorer.wt
-rw-r--r--  1 root root    95 May 21 08:42 storage.bson
-rw-r--r--  1 root root    49 May 21 08:42 WiredTiger
-rw-r--r--  1 root root  4096 May 21 08:42 WiredTigerLAS.wt
-rw-r--r--  1 root root    21 May 21 08:42 WiredTiger.lock
-rw-r--r--  1 root root   994 May 21 08:45 WiredTiger.turtle
-rw-r--r--  1 root root 61440 May 21 08:45 WiredTiger.wt
  1. Shutdown the previous mongod instance.

 

  1. Create a new db path and start mongod with --directoryperdb option:
mkdir /data/newdb
/data/mongodb/bin/mongod --dbpath /data/newdb --directoryperdb
  1. Connect to the mongo shell, create a test db, and insert a sample document:
mongo localhost:27017
> use mydb
> db.mycol.insert({bar:1})
  1. Inspect the /data/newdb directory structure, it should look something like this:
ls /data/newdb
total 108
drwxr-xr-x  7 root root  4096 May 21 08:42 .
drwxr-xr-x 10 root root  4096 May 21 08:42 ..
drwxr-xr-x  2 root root  4096 May 21 08:41 admin
drwxr-xr-x  2 root root  4096 May 21 08:42 diagnostic.data
drwxr-xr-x  2 root root  4096 May 21 08:41 journal
drwxr-xr-x  2 root root  4096 May 21 08:41 local
-rw-r--r--  1 root root 16384 May 21 08:42 _mdb_catalog.wt
-rw-r--r--  1 root root     0 May 21 08:42 mongod.lock
drwxr-xr-x  2 root root  4096 May 21 08:41 mydb
-rw-r--r--  1 root root 16384 May 21 08:42 sizeStorer.wt
-rw-r--r--  1 root root    95 May 21 08:41 storage.bson
-rw-r--r--  1 root root    49 May 21 08:41 WiredTiger
-rw-r--r--  1 root root  4096 May 21 08:42 WiredTigerLAS.wt
-rw-r--r--  1 root root    21 May 21 08:41 WiredTiger.lock
-rw-r--r--  1 root root   986 May 21 08:42 WiredTiger.turtle
-rw-r--r--  1 root root 28672 May 21 08:42 WiredTiger.wt

How it works...

We start by running a mongod instance with no special parameters except for --dbpath. In step 2, we create a new database mydb and insert a document in the collection mycol, using the mongo shell. By doing this, the data files for this new db are created and can be seen by inspecting the directory structure of our main database path /data/db. In that, among other files, you can see that database files begin with collection-<number> and its relevant index file begins with index-<number>. As we guessed, all databases and their relevant files are within the same directory as our db path.

If you are curious and wish to find the correlation between the files and the db, then run the following commands in mongo shell:

> use mydb
> var curiosity = db.mycol.stats()
> curiosity['wiredTiger']['uri']
statistics:table:collection-5-626293768203557661

The last part of this string that is, collection-5-626293768203557661 corresponds to the file in our /data/db path.

Moving on, in steps 4 and step 5, we stop the previous mongod instance, create a new path for our data files and start a new mongod instance but this time with the --directoryperdb parameter. As before, in step 6 we insert some random data in the mycol collection of a new database called mydb. In step 7, we look at the directory listing of our data path and we can see that there is a subdirectory in the data path which, as you guessed, matches our database name mydb. If you look inside this directory that is, /data/newdb/mydb, you should see a collection and an index file.

So one might ask, why go through all this trouble for having separate directories for databases? Well, in certain application scenarios, if your database workloads are significantly high, you should consider storing the database on a separate disk/volume. Ideally, this should be a physically separate disk or a RAID volume created using separate physical disks. This ensures the separation of disk I/O from other operations including MongoDB journals. Additionally, this also helps you separate your fault domains. One thing you should keep in mind is that journals are stored separately, that is, outside the database's directory. So, using separate disks for databases allows the journals to not content for same disk I/O path.

 

Customizing the MongoDB configuration file


In all the previous recipes of this chapter, we have passed command line flags to the mongod daemon. In this recipe, we will look at how to use the config file as an alternative to passing command line flags.

Getting ready

Nothing special, just make sure you have a MongoDB database installation ready.

How to do it..

  1. Start your favorite text editor and add the following in a file called mongod.conf:
storage:
  dbPath: /data/db
  engine: wiredTiger
  directoryPerDB: true
net:
  port: 27000
  bindIp: 127.0.0.1
  ssl:
    mode: requireSSL
    PEMKeyFile: /data/mongo-secure.pem
  1. Start your mongod instance:
mongodb/bin/mongod --config /data/mongod.conf

How it works...

MongoDB allows passing command line parameters to mongod using a YAML file. In step 1, we are creating a config file called mongod.conf. We add all the previously used command line parameters from this chapter, into this config file in YAML format. A quick look at the file's content should make it clear that the parameters are divided into sections and relevant subsections. Next, in step 2, we start the mongod instance, but this time with just one parameter --config followed by the path of our config file.

As we saw in earlier recipes, although passing configuration parameters seems normal, it is highly advisable that one should use configuration files instead. Having all parameters in a single configuration file not only makes it easier in terms of viewing the parameters but also helps us programmatically (YAML FTW!) inspect and manage the values of these variables. This simplifies operations and reduces the chance of errors.

There's more...

Do have a look at other parameters available in the configuration file https://docs.mongodb.com/manual/reference/configuration-options/.

 

Running MongoDB as a Docker container


In this recipe, we will look at how to run MongoDB as a Docker container. I will assume that you are familiar with the bare minimum understanding of how Docker works. If you are not, have a look at https://www.docker.com/what-container. It should help you get acquainted with Docker's concepts.

Getting ready

Make sure you have Docker installed on your system. If you are using Linux, then it is highly advisable to use kernel version 3.16 or higher.

How to do it...

  1. Download the latest MongoDB Docker image:
docker pull mongo:3.4.4
  1. Check that the image exists:
docker images
  1. Start a container:
docker run -d -v /data/db:/data/db --name mymongo mongo:3.4.4
  1. Check if the container is running successfully:
docker ps
  1. Let's connect to our mongo server using the mongo client from the container:
docker exec -it mymongo mongo
  1. Stop the mongo instance and with host mode networking:
docker run -d -v /data/db:/data/db --name mymongo --net=host mongo:3.4.4 --bind_ip 127.0.0.1 --port 27000
  1. Connect to the new instance using mongo shell:
docker exec -it mymongo mongo localhost:27000

How it works...

In step 1, we fetched the official MongoDB image, from Docker's public repository. You can view it at https://hub.docker.com/_/mongo/. While fetching the image we explicitly mentioned the version that is, mongo:3.4.4.. Although mentioning the version (also known as Docker image tag) is optional, it is highly advisable that when you download any application images via Docker, always fetch them with the relevant tag. Otherwise, you might end up fetching the latest tag and as they change often, you would end up running different versions of you applications.

Next, in step 2, we run the docker images command which shows us a list of images available on the server, in our case it should show you the MongoDB image with the tag 3.4.4 available for use.

In step 3, we start a container in detached (-d) mode. As all containers use ephemeral storage and as we wish to retain the data, we mount a volume (-v) by providing it a local path /data/db that can be mounted to the container's internal directory /data/db. This ensures that even if the container is stopped/removed, our data on the host machine is retained on the host's /data/db path. At this point, one could also use Docker's volumes, but in order to keep things simplified, I prefer using a regular directory. Next, in the command we provide a name (--name) for our container. This is followed by the Docker image and tag that should be used to run the container, in our case it would be mongo:3.4.4. When you enter the command, you should get a large string as a return value, this is your new container's ID.

In step 4, we run the docker ps command which shows us a list of running containers. If, in case your container is stopped or exited, use docker ps -a to show all containers. In the output you can see the container's details. By default, Docker starts a container in bridge mode that is, when Docker is installed, it creates a bridge interface on the host and the resulting containers are run using a virtual network device attached to the bridge. This results in complete network isolation of the container. Thus, in our case, if we wish to connect to the container's mongod instance on 27017, we would need to explicitly expose TCP port 27017 to the base host or bind the base host's port to that of the container thus allowing an external MongoDB client to connect to our instance. You can read more about Docker's networking architecture at https://docs.docker.com/engine/userguide/networking/.

In step 5, we execute the mongo shell command from the container to connect to the mongod instance. The official MongoDB container image also takes in command-line flags, by passing them in the docker run command. We do this in step 6 along with running the container in host mode networking. Host mode networking binds the server's network namespace onto the container thus bypassing the bridge interface. We pass the --bind_ip and --port flags to the docker run command which instructs mongod to bind to 127.0.0.1:27000. As we are using host mode networking, the mongod daemon would effectively bind to the base host's loopback interface. In step 7, we connect to our new MongoDB instance but this time we explicitly provide the connection address.

There's more..

If you ever wish to debug the container, you can always run the container in the foreground by passing the -it parameters in place of -d. Additionally, try running the following command and check the output:

docker logs mymongo

Lastly, I would suggest you have a look at the start scripts used by this container's image to understand how configurations are templatized. It will definitely give you some pointers that will help when you are setting up your own MongoDB container.

With this recipe, we conclude this chapter. I hope these recipes have helped you gear up for getting started with MongoDB. As all things go, no amount of text can replace actual practice. So I sincerely request you to get your hands dirty and attempt these recipes yourself.

In the next chapter, we will take a closer look at MongoDB's indexes and how they can be leveraged to gain a tremendous performance boost in data retrieval.

 

 

 

About the Author

  • Cyrus Dasadia

    Cyrus Dasadia has enjoyed tinkering with open source projects since 1996. He has been working as a Linux system administrator and part-time programmer for over a decade. He works at InMobi, where he loves designing tools and platforms. His love for MongoDB blossomed in 2013, when he was amazed by its ease of use and stability. Since then, almost all of his projects have been written with MongoDB as the primary backend. Cyrus is also the creator of an open source alert management system called CitoEngine. His spare time is devoted to trying to reverse-engineer software, playing computer games, or increasing his silliness quotient by watching reruns of Monty Python.

    Browse publications by this author

Latest Reviews

(1 reviews total)
this is very good book for mongodb developer.
MongoDB Administrator's Guide
Unlock this book and the full library FREE for 7 days
Start now