MongoDB with Credential in C#

MongoDB with Credential in C#




Open command prompt and goto C:\Program Files\MongoDB\Server\4.1\bin>


1.mongod --port 12345

2.mongo --port 12345

3.use admin;

4.db.createUser(
  {
    user: "admin",
    pwd: "admin143#",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
);

5.Restart mongodb instance

6.mongod --auth --port 12345

7.mongo --port 12345 -u "admin" -p "admin143#" --authenticationDatabase "admin"

8.use dbname

9.db.createUser(
  {
    user: "User1",
    pwd: "User1143#",
    roles: [ { role: "readWrite", db: "dbname" },
             { role: "read", db: "reporting" } ]
  }
);

Restart mongodb instance

10.  Install MongoDB Service
 mongod.exe --config "D:\MongoDB\demodb.conf" --service --install --serviceName "MongoDB DemoDB 12345" --serviceDisplayName "MongoDB DemoDB 12345" --auth 
 

 mongoDB usage with C# with credential

Sample code


//Create instance 
MongoUrl url = new MongoUrl("mongodb://username:password@hostname:port/demo");
MongoClient client = new MongoClient(url);
 
//Get Database 
var database = client.GetDatabase(url.DatabaseName);
 
//Read collection
IMongoCollection<Users> tempCollection  = database.GetCollection<classname>("collectionname");
 
//Result data
List<classname> resultData = tempCollection.AsQueryable().Where<classname>(a => a.propertyname == value).ToList();
 
  
Hope this will help you and save your time.

Enjoy !!!

:)

No comments:

Post a Comment