Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a database user in MongoDB using Java

Tags:

java

mongodb

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

like image 951
Amar Avatar asked May 28 '15 11:05

Amar


2 Answers

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);
like image 167
Dev Avatar answered Nov 13 '22 01:11

Dev


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);
like image 37
kukudas Avatar answered Nov 13 '22 01:11

kukudas