Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a user in MongoDB

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?

like image 503
iefpw Avatar asked Apr 08 '14 18:04

iefpw


1 Answers

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);
like image 53
Ethan Avatar answered Oct 01 '22 06:10

Ethan