Create a database user in MongoDB using Java

476 views
Skip to first unread message

Amar

unread,
May 28, 2015, 9:35:49 AM5/28/15
to mongod...@googlegroups.com
Hi All,

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 a 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.T








Jeff Yemin

unread,
May 28, 2015, 11:25:34 AM5/28/15
to mongod...@googlegroups.com
Try something like this: https://gist.github.com/anonymous/40291bfd75eea9078e5f

See the documentation for the createUser and usersInfo commands for more information.


Regards,
Jeff 

Amar

unread,
May 30, 2015, 1:14:55 PM5/30/15
to mongod...@googlegroups.com
Thanq Jeff. It was very helpful to me.
Reply all
Reply to author
Forward
0 new messages