MongoDB is a database engine that provides access to non-relational, document-oriented databases. This tutorial will show you how to install and configure MongoDB on Ubuntu. We will also explain on some basic features and functions of the database.
Note that, this guide is specifically written for Ubuntu 18.04, 19.04, 19.10, 20.04 and Debian 9, 10.
Note that, this guide is specifically written for Ubuntu 18.04, 19.04, 19.10, 20.04 and Debian 9, 10.
Prerequisites
To follow this guide, you will need one (physical or virtual) machine installed with Ubuntu or Debian having sudo non-root user privileges. You should set correct timezone on your server with below command:
sudo timedatectl list-timezonessudo timedatectl set-timezone Asia/Karachi
You should set hostname of your server with below command:
sudo hostnamectl set-hostname your_server_name
Adding MongoDB Repository
Import the MongoDB public GPG key for package signing:sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 4b7c549a058f8b6b
Add the MongoDB repository to your sources.list.d directory:
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
Installing MongoDB
Now that the MongoDB repository has been added, we’re ready to install the latest stable version of MongoDB:sudo apt -y install mongodb-org
Configuring MongoDB
The configuration file for MongoDB is located at /etc/mongod.conf, and is written in YAML format.We highly recommend uncommenting the security section by removing # and adding the authorization: enabled string like below:
sudo nano /etc/mongod.conf
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
# how the process runs
processManagement:
timeZoneInfo: /usr/share/zoneinfo
security:
authorization: enabled
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
Save and close file when you are finished.
The authorization option enables role-based access control for your databases. If no value is specified, any user will have the ability to modify any database. We'll explain it to you how to create database users and set their permissions later in this guide.
Start and Stop MongoDB
To start, restart, or stop the MongoDB service, type the appropriate command from the following:sudo systemctl start mongod
sudo systemctl restart mongod
sudo systemctl stop mongod
You can also enable MongoDB to start on boot:
sudo systemctl enable mongod
Creating Database Users
If you enabled role-based access control in the Configuring MongoDB section, create a user administrator with credentials for use on the database:
mongo
By default, MongoDB connects to a database called test. Before adding any users, create a database to store user data for authentication:
use admin
Use the following command to create an administrative user with the ability to create other users on any database. For better security, change the values mongo-admin and password:
db.createUser({user: "dbadmin", pwd: "P@ssw0rd", roles:[{role: "userAdminAnyDatabase", db: "admin"}]})
Keep these credentials in a safe place for future reference. The output will display all the information written to the database except the password:
Type below to exit the mongo shell:
quit()
Now, test your connection to MongoDB with the newly created credentials:
mongo -u dbadmin -p --authenticationDatabase admin
The -u, -p, and --authenticationDatabase options in the above command are required in order to authenticate connections to the shell. Without authentication, the MongoDB shell can be accessed but will not allow connections to databases.
As the dbadmin user, create a new database to store regular user data for authentication. The following example calls this database user-db:
use user-db
db.createUser({user: "dbuser1", pwd: "password", roles:[{role: "read", db: "user-db"}, {role:"readWrite", db: "testDB"}]})
The similar to the following output will display all the information written to the database except the password:
Successfully added user: {
"user" : "dbuser1",
"roles" : [
{
"role" : "read",
"db" : "user-db"
},
{
"role" : "readWrite",
"db" : "testDB"
}
]
}
To create additional users, repeat these steps as the administrative user, creating new usernames, passwords and roles by substituting the appropriate values.
quit()
Managing Data and Collections
This section will explain a few basic features, but we encourage you to do further research based on your specific use case.
mongo -u dbuser1 -p --authenticationDatabase user-db
Create a new database, for example testDB:
use testDB
Make sure that this database name corresponds with the one for which the user has read and write permissions (we already added these permissions in previous step).
To show the name of the current working database, run the db command. Create a new collection, for example testDBCollection:
db.createCollection("testdbCollection", {capped: false})
If you’re not familiar with MongoDB terminology, you can think of a collection as analogous to a table in a relational database management system.
Create sample data for entry into the test database. MongoDB accepts input as documents in the form of JSON objects such as those below. The a and b variables are used to simplify entry; objects can be inserted directly via functions as well.
var a = { name : "M Anwar", attributes: { age : 34, address : "21 Fish St", phone : 03218675309 }}var b = { name : "F Kamal", attributes: { age : 30, address : "31 Main Rd", favorites : { food : "Burgers", animal : "Cat" } }}
Note that documents inserted into a collection need not have the same schema, which is one of many benefits of using a NoSQL database. Insert the data into testDBCollection, using the insert method:
db.testDBCollection.insert(a)
db.testDBCollection.insert(b)
The output for each of these operations will show the number of objects successfully written to the current working database:
WriteResult({ "nInserted" : 1 })
Confirm that the testCollection was properly created:
show collections
The output will list all collections containing data within the current working database:
testDBCollection
View unfiltered data in the testDBCollection using the find method. This returns up to the first 20 documents in a collection, if a query is not passed:
db.testDBCollection.find()
The output will show the similar to the following:
{ "_id" : ObjectId("471a2e6507d0fcd67baef07f"), "name" : "M Anwar" }
{ "_id" : ObjectId("471a2e7607d0fcd67baef080"), "age" : 34 }
You may notice the objects we entered are preceded by _id keys and ObjectId values. These are unique indexes generated by MongoDB when an _id value is not explicitly defined. ObjectId values can be used as primary keys when entering queries, although for ease of use, you may wish to create your own index as you would with any other database system.
The find method can also be used to search for a specific document or field by entering a search term parameter (in the form of an object) rather than leaving it empty. For example:
db.testDBCollection.find({"name" : "M Anwar"})
Running the command above returns a list of documents containing the {"name" : "M Anwar"} object. To view the available options or how to use a particular method, append .help() to the end of your commands. For example, to see a list of options for the find method
db.testDBCollection.find().help()
Wrapping up
You now have a ready to use MongoDB database for your production. In our next guide, we'll show you how to create a highly available MongoDB Shard Cluster for your production environment.