问题
I'm using the latest version of the driver and MongoDB database 2.6 and I used to create users using the following code:
MongoUser _user1 = new MongoUser("username", "password", false);
MongoDatabase.AddUser(_user1);
and now it is saying MongoDatabase.AddUser()
is deprecated by showing the following information:
...is obsolete: Use the new user management command 'createUser' or 'updateUser'."
Where is this new user management command? How do I create a user using the new MongoDB C# driver?
回答1:
I did a search for 'createUser' on the latest code on the GitHub repository: https://github.com/mongodb/mongo-csharp-driver/search?q=createUser&ref=cmdform
At the time of writing, the only reference to 'createUser' is here
The method has been marked as obsolete however in this commit
However; on closer inspection of the code, I see this:
if (_server.RequestConnection.ServerInstance.Supports(FeatureId.UserManagementCommands))
{
AddUserWithUserManagementCommands(user);
}
else
{
AddUserWithInsert(user);
}
So, it is calling the required method under the hood
回答2:
For those interested in creating a user with the C# v2.0.1 driver and MongoDB v3.0.6 use the following:
var client = new MongoClient(connectionString);
var database = client.GetDatabase("database_to_create_user_in");
var user = new BsonDocument { { "createUser", "fred" }, { "pwd", "some_secure_password" }, { "roles", new BsonArray { new BsonDocument { { "role", "read" }, { "db", "database_to_create_user_in" } } } } };
await database.RunCommandAsync<BsonDocument>(user);
回答3:
I'm using MongoDB 2.6.2 and latest C# driver 1.9.2. This is how you can add new users with 'createUser':
public static void AddUser(string user, string password, string[] roles)
{
var database = GetDatabase();
var command = new CommandDocument { { "createUser", user}, { "pwd", password }, { "roles", new BsonArray(roles) } };
var result = database.RunCommand(command);
}
回答4:
For me I struggled with the roles. I wanted to add an admin (initial user) to the mongodb. My working solution looks like that.
private static bool CreateAdminUser(string databaseUser, string databasePassword)
{
try
{
var databaseName = "admin";
var user = new CommandDocument
{
{ "createUser", databaseUser },
{ "pwd", databasePassword },
{
"roles", new BsonArray
{
new BsonDocument { { "role", "readWriteAnyDatabase" }, { "db", databaseName } },
new BsonDocument { { "role", "userAdminAnyDatabase" }, { "db", databaseName } },
new BsonDocument { { "role", "dbAdminAnyDatabase" }, { "db", databaseName } }
}
}
};
new MongoClient().GetServer().GetDatabase(databaseName).RunCommand(user);
return true;
}
catch
{
return false;
}
}
来源:https://stackoverflow.com/questions/22945020/how-to-create-a-user-in-mongodb