Java + Database - Add Role to existing user, through Java

4

Use MongoDB with Java and need, through Java execute the following command in mongoDB:

db.grantRolesToUser( "joao", [ {role:"dbOwner",db:"loja"} ] )

That is, I need to add a role to an existing user, and I need to specify the database. After much breaking my head, I still can not find the right way. Remember that in the command I need to specify the database (as above), because at that moment I will be logged in the admin database, so I have to say that the command refers to the database store. I keep looking. But if anyone knows and can give me a clue, thank you!

    
asked by anonymous 06.01.2016 / 16:24

1 answer

3

I found the answer:

MongoClient client = new MongoClient(new MongoClientURI("mongodb://127.0.0.1:27017"));

MongoDatabase adminDatabase = client.getDatabase("admin");

adminDatabase.runCommand(new Document("grantRolesToUser", "paulo")
.append("roles", Collections.singletonList(new Document("role", "dbOwner").append("db", "loja"))));

adminDatabase.runCommand(new Document("grantRolesToUser", "paulo")
.append("roles", Collections.singletonList(new Document("role", "dbOwner").append("db", "comercio"))));

client.close();
    
12.01.2016 / 23:42