MONGODB SERVER INSTALLATION ON UBUNTU STEPS
Step 1: Install MongoDB
sudo apt install -y softwarecho "deb [ arch=amd64,arm64 ]
[Link] focal/mongodb-org/5.0
multiverse" | sudo tee
sudo apt install -y mongodb
wget -qO - [Link] |
sudo apt-key add -
echo "deb [ arch=amd64,arm64 ]
[Link] focal/mongodb-org/5.0
multiverse" | sudo tee
/etc/apt/[Link].d/[Link]
sudo apt update
sudo apt install -y mongodb-org
mongod --version
Step 2: Start and enable the MongoDB service
sudo systemctl status mongod
sudo systemctl start mongod
sudo systemctl status mongod
sudo systemctl enable mongod
Step 3: Create a database and a user in MongoDB
mongosh
By default, there are three databases that are created upon installation. These are
admin, config, and local. `To list the existing databases, run the command:
> show dbs
To create a database invoke the use command followed by the database name. For
example, to create a database called employees run the command:
> use employees
To confirm the database you can currently in, run the db command. In this case, you will
get employees as the output
> db
MongoDB provides a number of shell methods for managing your database. The
[Link] method allows you to create a new user in a database.
The method requires you to define the username and password of the user and any
roles that you wish to grant the user. This information is presented in JSON format.
Here is the syntax of how you can create a user called cherry with read and write roles
on the employees database.
[Link](
{
user: "cherry",
pwd: "some_password",
roles: [ { role: "readWrite", db: "employees" } ]
}
)
You can list the users created using the [Link]() method as shown.
[Link]();
Step 4: Secure MongoDB
In MongoDB, Authentication is not enabled by default, implying that any user with
access to the database server can view, add and delete data without any permissions.
This is a serious vulnerability that can cause a serious breach of your data. In light of
this, we will go a step further and demonstrate how you can secure MongoDB.
The first step is to create an administrative user and to do so, first, access the Mongo
Shell.
mongosh
Next, connect or switch to the admin database.
> use admin
Next, create the database user by pasting these lines and hitting ENTER on the
keyboard.
[Link](
{
user: "AdminCherry",
pwd: passwordPrompt(),
roles: [ { role: "userAdminAnyDatabase", db: "admin" },
"readWriteAnyDatabase" ]
}
)
Let us break down this code.
The user: "AdminCherry" line creates an Administrative user called AdminCherry.
The pwd: passwordPrompt() method prompts you for the administrative user’s
password. This is a safer alternative to the pwd: field which requires you to type the
password in cleartext.
The roles: [ { role: "userAdminAnyDatabase", db: "admin" },
"readWriteAnyDatabase" ] line specifies the roles granted to the administrative
user. Here, the Administrative user is granted read and write permissions to the admin
database. And since this role is defined in the admin database, the administrative user,
in effect, can read and modify all the databases in the cluster.
Here is the output after running the command.
To exit from the Mongo Shell, run the exit command or press CTRL + C.
With the Admin user in place, the next step is to enable authentication. To do this, open
the [Link] file.
sudo nano /etc/[Link]
Scroll down and locate the security section. Uncomment it and add the
authorization directive and set it to enabled.
security:
authorization: enabled
Note that the authorization parameter is indented while security has no space at
the beginning.
Save the changes and exit from the configuration file. To apply the changes, restart the
Mongo service as shown.
sudo systemctl restart mongod
Also, be sure to check if the service is running as expected.
sudo systemctl status mongod
Now login to Mongo Shell.
mongosh
This time around you will observe that the warnings have disappeared.
However, if you try to perform any database-related task such as viewing databases, you
will get some output indicating that authentication is required.
> show dbs
To log in with authentication, first, log out of the Mongo Shell by running the exit
command. Then log in using the administrative user using the following syntax.
mongosh "mongodb://adminuser@mongo-ip-address:27017"
Provide the administrative user’s password, and this time around, all the authentication
warnings that you encountered before will have disappeared.
From this point going forward, only the administrative user will have the privileges to
view, create and modify data in the databases.
Step 5: Configure MongoDB for remote access
By default, MongoDB is set to be accessed locally on the same server it is installed on.
To enable remote access, you need to edit the /etc/[Link] file which is the
main configuration file for MongoDB.
It contains settings for the database storage location, logging, networking, and process
management to mention a few.
So, access the configuration file using your text editor.
sudo nano /etc/[Link]
Locate the network interfaces section and pay attention to the bindIPvalue.
# network interfaces
net:
port: 27017
bindIp: [Link]
By default, MongoDB s bound to [Link] which is the loopback address interface. This
implies that MongoDB is only able to accept connections from the same server where it
is installed.
To allow remote access, add a comma, then followed by the Mongo server’s IP address.
bindIp: [Link], mongo-server-ip
Save the changes and exit the configuration file. To apply the changes made, restart the
MongoDB service.
sudo systemctl restart mongod
If you have UFW enabled, run the following command to allow incoming connections
from a remote machine.
sudo ufw allow from remote_machine_ip to any port 27017
To effect the changes, reload the firewall.
sudo ufw reload
Step 6: Access MongoDB remotely
There are a couple of ways of accessing the MongoDB shell remotely. You can use the
netcat utility to initiate a TCP connection to port 27017 which is the default port that
MongoDB listens to.
If the netcat is not installed on the client machine, install it as follows.
sudo apt install netcat
To establish a connection to the MongoDB server via port 27017, run the command:
nc -zv mongodb_server_ip 27017
The following output indicates that the connection was successful.
Output:
Connection to mongodb_server_ip 27017 port [tcp/*] succeeded!
Alternatively, you can log in using Mongo Shell as follows.
mongosh "mongodb://username@mongo_server_ip:27017"
The shell automatically prompts you for the admin user’s password.
💡 Pro Tip: When using Mongo Shell login option ensure that the version of Mongo shell
on both the client and remote MongoDB server is the same.
Step 7: Work with MongoDB database
There are quite a few database operations that you can carry out in MongoDB. For
example, you can create, retrieve, update and delete records from a database.
Insert data
To create a document in a collection, use the .insertOne() method. The method
supports several data types such as strings, integers, boolean values, and arrays.
In the previous step, we created a test database called employees. We will now create a
collection and add a few documents. A collection comprises one or more documents
The command below creates a collection called staff and adds a document with some
user data as shown.
[Link]({ name: "Alice", age: 25, city: "London",
married: true, hobbies: ["Travelling", "Swimming", "Cooking"] })
Once the command successfully executes you will get the following output.
Output:
acknowledged: true,
insertedId: ObjectId("62647ff866c1f054568a11b5")
Retrieve data
With a document already created in the staff collection, you can retrieve it and filter
the results using the .find() method.
For example, to retrieve all the documents in the staff collection, run the command:
[Link]()
Output:
{
_id: ObjectId("62647ff866c1f054568a11b5"),
name: 'Alice',
age: 25,
city: 'London',
married: true,
hobbies: [ 'Travelling', 'Swimming', 'Cooking' ]