实体类:
using MongoDB.Bson; namespace WindowsFormsApp { class User { //public ObjectId _id; //BsonType.ObjectId 这个对应了 MongoDB.Bson.ObjectId public int UserId { get; set; } public string UserName { get; set; } public string Password { get; set; } } }
测试代码:
using System; using System.Windows.Forms; using MongoDB.Driver; namespace WindowsFormsApp { public partial class frmMongoDBTest : Form { //数据库连接字符串 string conn = "mongodb://127.0.0.1:27017"; //数据库名称 string database = "RsdfDb"; public frmMongoDBTest() { InitializeComponent(); } /// <summary> /// 插入数据 /// </summary> public void InsertData() { //创建数据库链接 var Server = new MongoClient(conn).GetServer(); //获得数据库RsdfDb var db = Server.GetDatabase(database); User user = new User(); user.UserId = 0; user.UserName = "admin"; user.Password = "1"; //获得Act_User集合,如果数据库中没有,先新建一个 var col = db.GetCollection("Act_User"); //执行插入操作 col.Insert<User>(user); user = new User(); user.UserId = 1; user.UserName = "chenqp"; user.Password = "1"; //获得Act_User集合,如果数据库中没有,先新建一个 col = db.GetCollection("Act_User"); //执行插入操作 col.Insert<User>(user); user = new User(); user.UserId = 2; user.UserName = "yangh"; user.Password = "1"; //获得Act_User集合,如果数据库中没有,先新建一个 col = db.GetCollection("Act_User"); //执行插入操作 col.Insert<User>(user); } /// <summary> /// 更新数据 /// </summary> public void UpdateData() { //创建数据库链接 var Server = new MongoClient(conn).GetServer(); //获得数据库RsdfDb var db = Server.GetDatabase(database); //获取Act_User集合 var col = db.GetCollection("Act_User"); //定义获取“UserName”值为“admin”的查询条件 var query = new QueryDocument { { "UserName", "admin" } }; //定义更新文档 var update = new UpdateDocument { { "$set", new QueryDocument { { "Password", "admin" } } } }; //执行更新操作 col.Update(query, update); } /// <summary> /// 删除数据 /// </summary> public void DeleteData() { //创建数据库链接 var Server = new MongoClient(conn).GetServer(); //获得数据库RsdfDb var db = Server.GetDatabase(database); //获取Act_User集合 var col = db.GetCollection("Act_User"); //定义获取“UserName”值为“admin”的查询条件 var query = new QueryDocument { { "Password", "admin" } }; //执行删除操作 col.Remove(query); } /// <summary> /// 查询数据 /// </summary> public void QueryData() { //创建数据库链接 var Server = new MongoClient(conn).GetServer(); //获得数据库RsdfDb var db = Server.GetDatabase(database); //获取Act_User集合 var col = db.GetCollection("Act_User"); //定义获取“UserName”值为“admin”的查询条件 var query = new QueryDocument { { "UserName", "chenqp" } }; //查询全部集合里的数据 var result1 = col.FindAllAs<User>(); //查询指定查询条件的第一条数据,查询条件可缺省。 var result2 = col.FindOneAs<User>(); //查询指定查询条件的全部数据 var result3 = col.FindAs<User>(query); } private void btnInsert_Click(object sender, EventArgs e) { InsertData(); lblResult.Text = "Insert Data completed"; } private void btnUpdate_Click(object sender, EventArgs e) { UpdateData(); lblResult.Text = "Update Data completed"; } private void btnDelete_Click(object sender, EventArgs e) { DeleteData(); lblResult.Text = "Delete Data completed"; } private void btnQuery_Click(object sender, EventArgs e) { QueryData(); } } }