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:
Note: I am using a JAVA library.
Can anybody please help me on this. I stuck over here.
Thanks & Regards, Amar
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With