C#中使用1.7版本驱动操作MongoDB简单例子

2019-12-26 11:21:44王旭
易采站长站为您分析C#中使用1.7版本驱动操作MongoDB简单例子,本文给出了连接MongoDB、操作MongoDB数据等例子,需要的朋友可以参考下    

 

复制代码
//创建数据库链接
//在1.7的版本驱动中这样写是会报 MongoServer方法已过时的
//MongoServer server =  MongoDB.Driver.MongoServer.Create(strconn); 

 


//带有用户名,密码的如下写法,不带的则直接ip+端口就可以
const string connectionString = "mongodb://city:liyang@192.168.1.211:27017";
//得到一个客户端对象的引用                    GetServer()对服务器对象的引用           
var Server = new MongoClient(connectionString).GetServer();
//到一个数据库对象的引用 
var client = Server.GetDatabase("City");
//对一组对象的引用
var collection = client.GetCollection<citys>("citys");

//插入一个 实体 
for (int i = 0; i < dt.Rows.Count; i++)
{
    collection.Insert(new citys
    {
        province = dt.Rows[i][0].ToString(),
        city = dt.Rows[i][1].ToString(),
        county = dt.Rows[i][2].ToString(),
        areacode = "0" + dt.Rows[i][3].ToString(),
        postalcode = dt.Rows[i][3].ToString()
    });
}

 

以下是git上的帮助文档  地址是:http://www.easck.com/ecosystem/tutorial/getting-started-with-csharp-driver/
将一个引用添加到c#司机dll

右键单击 引用 文件夹在Visual Studio的解决方案 探险家和选择 添加 参考…… 。 导航到文件夹 c#驱动程序dll被安装并添加一个引用以下 dll: