How to configure a MongoDB

MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents…

How to configure a MongoDB
Photo by tripleMdesignz on Unsplash

MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schema. MongoDB is used by many modern web applications to store data in a non-relational way. It is used by companies such as eBay, MetLife,Expedia and LoopCV (LoopCV offers a super cool service which allows users to upload their CV and automatically apply for jobs based on location and skills). In this article we will learn how to install and configure MongoDB.

Install MongoDB

In this article we will install MongoDB 4.4 which is two major versions behind at the time i wrote this article, but most of the options are still valid for the latest version (6.0). The system we installed MongoDB is AMI Linux 2 but the procedure should be the same for every RPM based system with the correct repo. In this particular case i use the repo intended with use for AMI Linux 2.

Create file /etc/yum.repos.d/mongodb-org-4.4.repo with the following contents

[mongodb-org-4.4] 
name=MongoDB Repository 
baseurl=https://repo.mongodb.org/yum/amazon/2/mongodb-org/4.4/x86_64/ 
gpgcheck=1 
enabled=1 
gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc

Now enter the following commands to update the package manager and install the needed packages for MongoDB.

sudo yum update 
sudo yum install -y mongodb-org

If no errors appeared on screen everything should be ok and ready to create our configuration files.

Why we configure MongoDB as a single primary instance replica

In this article we will configure MongoDB as a single instance of a replica set with the host being assigned the Primary role, we do this for two reasons

  • Currently we don't have the need nor the resources to create a replica set for high availability and read scaling, but if we need this in the feature it would be super easy to add another host to the replica set without any downtime!
  • We need Oplog, Oplog is a special capped collection that keeps a rolling record of all operations that modify the data stored in a MongoDB instance, without Oplog we cannot do incremental backups which we need!

Creating a MongoDB configuration file

I create the following file as /etc/mongod.conf , I explain in comments how this configuration works, not in full detail but the details you need to start working with!

# Logs are saved as file in the path location 
# logRotate: reopen is needed for the Linux logrotate tool to work with 
systemLog: 
  destination: file 
  logAppend: true 
  path: /var/log/mongodb/mongod.log 
  logRotate: reopen 
 
# Use 1.5GB Of RAM as Data Cache 
storage: 
  wiredTiger: 
    engineConfig: 
      cacheSizeGB: 1.5 
 
# Database will be saved at dbPath 
storage: 
  dbPath: /data/rs0 
  journal: 
    enabled: true 
  directoryPerDB: true 
 
# Time will be in UTC 
processManagement: 
  timeZoneInfo: /usr/share/zoneinfo 
 
# MongoDB will listen at all interfaces on port 27017 
net: 
  port: 27017 
  bindIp: 0.0.0.0   
 
# We will force authorization but for now comment out the 
# authorization and keyFile entries 
# The keyFile entry is needed for the replicas mode despite we have only 
# one instance 
security: 
  #authorization: "enabled" 
  #keyFile: /data/key.crt  
 
# The replica set name would be rs0 and the oplog size will be 256MB 
replication: 
  oplogSizeMB: 256 
  replSetName: "rs0"

Creating paths and key

Now we need to prepare some directories and the key that the replica will use!

  • Database Path
$ sudo mkdir -p /data/rs0 
$ sudo chown -R mongod: /data
  • Key File

The following commands will create a key, set the owner of the key as mongod user, set the rights to 600. (read/write for mongod user only)

$ sudo openssl rand -base64 756 > /data/key.crt 
$ sudo chown mongod: /data/key.crt  
$ sudo chmod 600 /data/key.crt

Creating Users from mongo shell

Now we need to create the admin user, the admin user will have rights to every database on this system, we can create users through the mongo shell, to enter mongo shell:

$ mongo

When the mongo shell prompt appears enter:

use admin 
db.createUser({ user: "admin" , pwd: "my_password", roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]})

With the above commands we switched to the admin database and we created the admin user with a password and the necessary rights to manage any database on the system, of course i recommend you to use a different and more complex password.

Now we will create a database named “work”, in MongoDB a database is actually created when there are some data in, so we will create a collection named “test” for the “work” database

use work 
db.createCollection("test")

Now we will create an administrator user for the work database in order not to use the admin database for all databases. This user will have rights to restore and backup the database, the rights for backup and restore are only available as part of the admin database.

use work 
db.createUser({ user: "work_admin", pwd: "my_password", roles:  [ { role : "restore", db : "admin" },{ role : "backup", db : "admin" }]})

Now let's assume that this database is used by an API for read and write purposes and we need to create one user for read operations and one for write

db.createUser({ user: "work_write", pwd: "my_password", roles: [{ role: "readWrite", db: "work" }]}) 
db.createUser({ user: "work_read", pwd: "my_password", roles: [{ role: "read", db: "work" }]})

Configuring the host as a single primary replica instance

Next step is to configure the one host replica set as primary!

use admin 
cfg = {"_id" : "rs0","members" : [{"_id" : 0,"host" : "127.0.0.1:27017"}]} 
rs.initiate(cfg) 
rs.conf() 
db.isMaster()

Uncomment configuration and restart MongoDB for settings to take effect

If you remember we have the following settings commented out, we need to uncomment them and restart MongoDB for authorization settings to take effect

security: 
  authorization: "enabled" 
  keyFile: /data/key.crt

And then

sudo systemctl restart mongod

If everything gone ok the one host replica set should be ready to use!

Conclusion

MongoDB is an incredibly powerful and versatile database system that can be used for a variety of applications. It is easy to set up and use, and provides a wide range of features and capabilities. MongoDB is a great choice for businesses that need a reliable and scalable database system. It is also a great choice for developers who need a powerful and flexible database system. MongoDB is a great choice for anyone looking for a powerful and reliable database system.

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…