Amar
Amar

Reputation: 763

Create a database user in MongoDB using Java

I am very new to MongoDB. I am trying to creating an user for a database in MongoDB through Java Driver. I am using mongo-java-driver 3.0.1 version. I searched on the google and I didn't find the relevant answers. I saw there was direct method in mongo-java-driver 2.13.0 but that was deprecated in the latest versions. I tried to use the following code to create an user but I am getting the exception.

Code:

MongoClient mongoClient = new MongoClient("127.0.0.1","27017");
MongoDatabase mongoDatabase = this.mongoClient
                        .getDatabase(doc);
BasicDBObject commandArguments = new BasicDBObject();
commandArguments.put("user", mongoDatabase.getName());
commandArguments.put("pwd", "Cip#erCloud@123");
String[] roles = { "readWrite" };
commandArguments.put("roles", roles);
BasicDBObject command = new BasicDBObject("createUser",
                        commandArguments.toString());
mongoDatabase.runCommand(command);

Exception:

com.mongodb.MongoCommandException: Command failed with error 2: 'Must provide a 'pwd' field for all user documents, except those with '$external' as the user's source db' on server 127.0.0.1:27017. 
The full response is { "ok" : 0.0, "errmsg" : "Must provide a 'pwd' field for all user documents, except those with '$external' as the user's source db", "code" : 2 }

Here are my questions:

  1. How to create users for a database.?
  2. How to get all the users for a database.?

Note: I am using a JAVA library.

Can anybody please help me on this. I stuck over here.

Thanks & Regards, Amar

Upvotes: 6

Views: 7089

Answers (4)

Bob Melander
Bob Melander

Reputation: 26

Regarding the code in the answer from Devender where a HashMap was used:

Map<String, Object> commandArguments = new HashMap<>();

The HashMap does not guarantee the order of the items when iterated over so the runCommand request may then fail if let's say 'roles' happen to come first. I encountered that issue.

Using LinkedHashMap instead of HashMap<> solved that issue as it normally iterates in the order of insertion.

Upvotes: 0

Robert Stewart
Robert Stewart

Reputation: 3330

I needed to create a user in a test case. Running the createUser command will throw an exception if the user already exists. I added some code to drop the user if it exists before trying to create the user, so that the exception wouldn't appear in the unit test logs. It was easier for me to add this code then to catch the exception, verify it was for an existing user account, and ignore it.

To use it, you need to set username, password, and TEST_DATABASE_NAME.

    Document result = null;
    MongoDatabase db = mongo.getDatabase(TEST_DATABASE_NAME);
    BasicDBObject getUsersInfoCommand = new BasicDBObject("usersInfo",
            new BasicDBObject("user", username).append("db", TEST_DATABASE_NAME));
    BasicDBObject dropUserCommand = new BasicDBObject("dropUser", username);
    BasicDBObject createUserCommand = new BasicDBObject("createUser", username).append("pwd", password).append("roles",
                        Collections.singletonList(new BasicDBObject("role", "dbOwner").append("db", TEST_DATABASE_NAME)));

    // If test user exists from a previous run, drop it
    result = db.runCommand(getUsersInfoCommand);
    ArrayList users = (ArrayList) result.get("users");
    if (!users.isEmpty()) {
        db.runCommand(dropUserCommand);
    }

    db.runCommand(createUserCommand);

Even better is to drop the user after the test is complete, but I have code in an @AfterClass method that is effectively part of this test, which would have made sharing this code example more complicated.

Upvotes: 1

kukudas
kukudas

Reputation: 4934

Both ways did not work for me. However this way worked:

 final MongoDatabase db = mongoClient.getDatabase("myDatabase");
 final BasicDBObject createUserCommand = new BasicDBObject("createUser", "myuser").append("pwd", "mypassword").append("roles",
                            Collections.singletonList(new BasicDBObject("role", "dbOwner").append("db", "myDatabase")));
            db.runCommand(createUserCommand);

Upvotes: 5

Dev
Dev

Reputation: 13753

Can you please try this for creating user:

    MongoClient mongo = new MongoClient("localhost", 27017);
    MongoDatabase db =  mongo.getDatabase("testDB");
    Map<String, Object> commandArguments = new HashMap<>();
    commandArguments.put("createUser", "dev");
    commandArguments.put("pwd", "password123");
    String[] roles = { "readWrite" };
    commandArguments.put("roles", roles);
    BasicDBObject command = new BasicDBObject(commandArguments);
    db.runCommand(command);

Upvotes: 12

Related Questions