How to Add Users and How to Manage MonogDB User Roles in Eclipse using Java

Introduction

This tutorial will show you the basic ways of adding MongoDB users and how to manage user roles in Eclipse using Java. You must have the MongoDB and the compatible MongoDB Java driver properly installed in order to manage user roles in Eclipse IDE. The examples in this tutorial use MongoDB version 4.0 and MongoDB Java Driver Version 3.8.2.

  • First, check to confirm the MongoDB and the compatible MongoDB Java driver are properly installed and configured on your machine before you begin.

  • Confirm that you also have the latest version of Java JDK properly installed and configured.

  • The examples in this tutorial will use Eclipse IDE.

How to start the MongoDB Database Daemon.

  • First, open your terminal by pressing the Ctrl + Alt + T keys.

  • Next, start the MongoDB service and check the status using the below command.

  • Use sudo command to avoid permission-related issues when starting the MongoDB service, as shown here:
sudo systemctl start mongod
sudo systemctl status mongod
  • The command should return something like the following:
● mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
   Active: active (running) since Mon 2019-04-22 19:27:02 PST; 8min ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 6598 (mongod)
   CGroup: /system.slice/mongod.service
           └─6598 /usr/bin/mongod --config /etc/mongod.conf

Apr 22 19:27:02 teamsolo systemd[1]: Started MongoDB Database Server.
lines 1-9/9 (END)

NOTE: The examples in this tutorial use MongoDB version 4.0 and MongoDB Java Driver Version 3.8.2.

The MongoDB Database Built-In Roles

Database User Roles

RoleDescription
readThe “read” role grants the ability to read the data on non-system collections, such as system.namespaces, system.js and the system.indexes.
readWriteThe “readWrite” role grants the privileges of the read role, however, it also grants the additional ability to modify data on all non-system collections and the system.js collection

How to Create MongoDB User and User Roles in Eclipse Using Java

  • The following script will create a user with corresponding roles in MongoDB using PHP:
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017"); // (1)
MongoDatabase db = mongo.getDatabase("myDatabase"); // (2)
BasicDBObject createUserCmd = new BasicDBObject("createUser", "Yeshua") // (3)
.append("pwd", "mypassword")
.append("roles",
Collections.singletonList( // (4)
new BasicDBObject(
"role", "readWrite").append("db", "myDatabase")
));
db.runCommand(createUserCmd); // (5)
  1. Instantiates MongoClient to connect to the MongoDB deployment.
  2. Accesses the database using the getDatabase() method.
  3. Creates a document in the MongoDB database using the BasicDBObject.
  4. Creates an empty list object (singltonList()) then adds another document (embedded) using the BasicDBObject.
  5. This line will execute the given command.
  • Use the following command to verify the user and the corresponding role was created:
db.getUser()
  • The returned results should resemble something like the following:
{
"_id" : "PlayerDB.Yeshua",
"userId" : UUID("f1cc8d1e-69cf-4917-86e8-0a3a53f255ea"),
"user" : "Yeshua",
"db" : "PlayerDB",
"roles" : [
{
"role" : "readWrite",
"db" : "myDatabase"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}

How to Manage MongoDB User Roles

  • While there are various ways of managing user roles, this section will demonstrate the basics on how to manage MongoDB user roles.

How to Update MongoDB User Roles

  • The below script will update the user role from readWrite to dbOwner using the updateUser() method:
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("PlayerDB");
BasicDBObject createUserCmd = new BasicDBObject("updateUser", "Yeshua")
.append("roles",
Collections.singletonList(new BasicDBObject("role", "dbOwner").append("db", "myDatabase")));
db.runCommand(createUserCmd);
  • Execute the following command in the Mongo terminal to verify the user role was properly updated:
db.getUser()
  • The returned results should resemble the following:
{
"_id" : "PlayerDB.Yeshua",
"userId" : UUID("f1cc8d1e-69cf-4917-86e8-0a3a53f255ea"),
"user" : "Yeshua",
"db" : "PlayerDB",
"roles" : [
{
"role" : "dbOwner",
"db" : "myDatabase"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}

How to Revoke MongoDB User Roles

  • Execute the following command to revoke a role using revokeRolesFromUser() method:
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("PlayerDB");
BasicDBObject createUserCmd = new BasicDBObject("revokeRolesFromUser", "Yeshua")
.append("roles",
Collections.singletonList(new BasicDBObject("role", "readWrite").append("db", "myDatabase")));
db.runCommand(createUserCmd);
  • Execute the following command in the Mongo terminal to confirm the user role was revoked:
db.getUser()
  • The results should return something that resembles the following script:
{
"_id" : "PlayerDB.Yeshua",
"userId" : UUID("f1cc8d1e-69cf-4917-86e8-0a3a53f255ea"),
"user" : "Yeshua",
"db" : "PlayerDB",
"roles" : [ ],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
  • Note that roles in the above script returns empty “[ ]”.

How to Grant User Roles

  • The following command will grant user roles to a specified user:
$dbName = 'abi_db';
$dbUser = 'rommel';

$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = array
(
"grantRolesToUser" => $dbUser,
"roles" => array
(
array("role" => "read", "db" => $dbName)
)
);
$result = $db->executeCommand('abi_db', new MongoDB\Driver\Command($command));
  • Execute the following command to verify the role was successfully granted:
> db.getUser("rommel")
{
"_id" : "abi_db.rommel",
"userId" : UUID("e4d98a44-9d09-4973-9bd1-dac0f9c55351"),
"user" : "rommel",
"db" : "abi_db",
"roles" : [
{
"role" : "read",
"db" : "abi_db"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}

Conclusion

This tutorial demonstrated how to go about adding MongoDB users and how to manage user roles in Eclipse using Java. This article showed you the basic ways of granting, changing and revoking users roles. Remember to always confirm that the changes in user role were successful.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.