简体   繁体   中英

MongoDB C# Driver failed to run database command authenticate

I want to authenticate to MongoDB with C# not through passing the Connection String/Credentials on the MongoClient() instance. It's like we do it on MongoDB Shell, We call monog -> db.auth(<username>,<password>) it means Connect to database first and authenticate after that.

  1. Write C# Code
    This is my code:

     var mongoClient = new MongoClient(); var testDB = mongoClient.GetDatabase("test"); string username = txtUserName.Text; string password = txtPassword.Password; // Check password var cmd = new BsonDocument("authenticate", new BsonDocument { {"username",username }, {"password",password } }); var queryResult = testDB.RunCommand<BsonDocument>(cmd); 

    My Code connect to MongoDB and call the authenticate Database Command ( described Here. It's not the db.auth() Shell method )to login with it

  2. Run MongoDB with --auth option.

  3. Run my Code.

After step 3, I encountered this problem. My code say

Additional information: Command authenticate failed: field missing/wrong type in received authenticate command.

I have read MongoDB documents (Also the link I added above) I can't find What I was missing.

I think you can use a JsonCommand to call eval function to execute db.auth function like this - not tested -:

var command = new JsonCommand<BsonDocument>(@"{ eval: ""db.auth(\""username\"", \""password\"");"" }");
var result = db.RunCommand(command);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM