Create a database user in MongoDB using Java

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);

Tags:

Java

Mongodb