数据库是对用户操作的,所以日常的对用户的管理也是一项重要的工作。接下来例子是新建用户、删除用户
C#类可以使用MongoDatabase类的AddUser(MongoCredentials credentials)方法为某个特定数据库建立用户,只有一个参数即证书。
1)条件:为test数据库增加一个新用户u1,密码:p1,使用AddUser方法,代码如下:
static void Main(string[] args)
{
//数据库连接字符串
string connectionString = "mongodb://root:root@127.0.0.1:27017";
//得到一个对象实例的连接
var client = new MongoClient(connectionString);
var server = client.GetServer();
MongoCredentials credentials = new MongoCredentials("wander", "123456");
MongoDatabase mydb = server.GetDatabase("test", credentials);
//新建一个证书,存储用户信息
MongoCredentials newUser = new MongoCredentials("u1", "p1");
//新建证书中指定的用户
mydb.AddUser(newUser);
}
注意:3.0之前版本可以MongoServer server = MongoServer.Create(connectionString);得到对象实例的连接
查找需要Shell里面输入
use test
db.system.users.find();
2)列出数据库test中的所有用户
static void Main(string[] args)
{
//数据库连接字符串
string connectionString = "mongodb://root:root@127.0.0.1:27017";
//得到一个对象实例的连接
var client = new MongoClient(connectionString);
var server = client.GetServer();
MongoCredentials credentials = new MongoCredentials("wander", "123456");
MongoDatabase mydb = server.GetDatabase("test", credentials);
//取数据库中所有用户
MongoUser[] userlist = mydb.FindAllUsers();//FindAllUsers是获取数据库中所有用户
foreach(var user in userlist)
{
Console.WriteLine(user.Username);
}
Console.ReadLine();
}
3)查询指定用户
static void Main(string[] args)
{
//数据库连接字符串
string connectionString = "mongodb://root:root@127.0.0.1:27017";
//得到一个对象实例的连接
var client = new MongoClient(connectionString);
var server = client.GetServer();
MongoCredentials credentials = new MongoCredentials("wander", "123456");
MongoDatabase mydb = server.GetDatabase("test", credentials);
//取数据库中所有用户
MongoUser user = mydb.FindUser("u1");
Console.WriteLine(user.Username);
Console.ReadLine();
}
//删除用户
static void Main(string[] args)
{
//数据库连接字符串
string connectionString = "mongodb://root:root@127.0.0.1:27017";
//得到一个对象实例的连接
var client = new MongoClient(connectionString);
var server = client.GetServer();
MongoCredentials credentials = new MongoCredentials("wander", "123456");
MongoDatabase mydb = server.GetDatabase("test", credentials);
//删除用户u1
mydb.RemoveUser("u1");
}
db.system.users.find()验证结果