Press Ctrl/Cmd + P to print
or save as PDF

3 Basics of Using MongoDB In Linux Based VPS

MongoDB is one of the most well-known NoSQL database managers. MongoDB is used for saving documents instead of data record such as SQL and applications that save data in formatted documents relies on it. MongoDB is also popular in environments that require a lot of scalabilities. You can quickly conduct replication procedures using MongoDB, allowing data scalability. MongoDB can be used by any application that needs to store semi-structured data.

In this article, we will be guiding you on the basics of using MongoDB in your Linux based VPS. The Linux distribution used in this tutorial is Ubuntu version 1804.

Creating Database

On MongoDB installation, there will be an existing database called admin by default. However, more databases are needed to ensure your project runs smoothly. To create more databases, firstly, open the MongoDB console.

mongo

You may create a database after opening the console. Note that, unlike SQL, there isn’t a specific command for creating a database. There is only the use command for using an existing database and if the database doesn’t exist, it will create by itself.

use <database_name>

Create User

MongoDB does not include an administrator account by default. You will need to start by creating users with specific permissions for each database. Access help in the MongoDB console.

help

You will be able to see a db.createUser()  function. To use this function, you will need to specify the name, password, database, and the role the user will have. As MongoDB receives parameters in JSON format, it is similar when creating a new user using the command as shown below.

db.createUser(
{
user: "<insert_name>",
pwd: "<insert_password>",
roles: [ { role: "userAdminAnyDatabase", db:"admin" } ]
}
)

There are more types of roles such as dbAdmin, dbUser, and so on. Visit the official MongoDB documentation to learn more about it and which suits your project best.

To review all the users created, run this command.

show users

Exit the MongoDB console and run the following command to test the operation.

exit
mongo -u [<user>] -p [<password>] [<host>:<port>]/[<database>]

Enable Remote Authentication

MongoDB authorizes all logs from the local machine by default. With authentication enabled, it might cause issues when the application is ready to be deployed. To prevent these problems, open the file “/etc/mongodb.conf” and comment on the line with “bindIP:127.0.0.1″.

sudo nano /etc/mongodb.conf

You may also modify the port of MongoDB on the same file. Make save changes and exit, then restart MongoDB to implement the changes.

sudo systemctl restart mongodb

Local users can now log in without authentication. Note that this step is optional and if you prefer to have tighter security, you can always remove the comment line or skip this step.