2015-05-28 119 views
4

MongoDB中的數據庫用戶我是很新的MongoDB的。我正在嘗試通過Java Driver在MongoDB中爲數據庫創建一個用戶。我使用蒙戈的Java驅動程序3.0.1版本。我搜索了谷歌,我沒有找到相關的答案。我看到有在蒙戈的Java驅動程序2.13.0直接方式,但在最新的版本中已過時。我試圖使用下面的代碼來創建一個用戶,但我得到了異常。創建使用Java

代碼:

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#[email protected]"); 
String[] roles = { "readWrite" }; 
commandArguments.put("roles", roles); 
BasicDBObject command = new BasicDBObject("createUser", 
         commandArguments.toString()); 
mongoDatabase.runCommand(command); 

例外:

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 } 

這裏是我的問題:

  1. 如何創建用戶提供一個數據庫?
  2. 如何獲得所有數據庫的用戶?

注意:我正在使用JAVA庫。

可有人請幫助我在此。我困在這裏。

感謝&問候,阿馬爾

回答

6

能否請您試試這個創建用戶:

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

Thanq其工作。 :) – Amar

2

兩種方式都沒有爲我工作。但是這樣的工作:

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