Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
MongoDB Administrator???s Guide
MongoDB Administrator???s Guide

MongoDB Administrator???s Guide: Over 100 practical recipes to efficiently maintain and administer your MongoDB solution

eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

MongoDB Administrator???s Guide

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.

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.

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.

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...

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • -Configure and deploy your MongoDB instance securely, without any hassle
  • -Optimize your database's query performance, perform scale-out operations, and make your database highly available
  • -Practical guide with a recipe-based approach to help you tackle any problem in the application and database administration aspects of MongoDB

Description

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.

Who is this book for?

Database administrators with a basic understanding of the features of MongoDB and who want to professionally configure, deploy, and administer a MongoDB database, will find this book essential. If you are a MongoDB developer and want to get into MongoDB administration, this book will also help you.

What you will learn

  • -Install and deploy MongoDB in production
  • -Manage and implement optimal indexes
  • -Optimize monitoring in MongoDB
  • -Fine-tune the performance of your queries
  • -Debug and diagnose your database s performance
  • -Optimize database backups and recovery and ensure high availability
  • -Make your MongoDB instance scalable
  • -Implement security and user authentication features in MongoDB
  • -Master optimal cloud deployment strategies
Estimated delivery fee Deliver to Lithuania

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 25, 2017
Length: 226 pages
Edition : 1st
Language : English
ISBN-13 : 9781787126480
Vendor :
MongoDB
Category :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Lithuania

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Oct 25, 2017
Length: 226 pages
Edition : 1st
Language : English
ISBN-13 : 9781787126480
Vendor :
MongoDB
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 99.97
MongoDB Cookbook - Second Edition
€36.99
Mastering MongoDB 3.x
€29.99
MongoDB Administrator???s Guide
€32.99
Total 99.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Installation and Configuration Chevron down icon Chevron up icon
Understanding and Managing Indexes Chevron down icon Chevron up icon
Performance Tuning Chevron down icon Chevron up icon
High Availability with Replication Chevron down icon Chevron up icon
High Scalability with Sharding Chevron down icon Chevron up icon
Managing MongoDB Backups Chevron down icon Chevron up icon
Restoring MongoDB from Backups Chevron down icon Chevron up icon
Monitoring MongoDB Chevron down icon Chevron up icon
Authentication and Security in MongoDB Chevron down icon Chevron up icon
Deploying MongoDB in Production Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
JackHeart Nov 13, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
GOOD FOR ME !
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela