连接MongoDB
MongoDB 不存在创建表 连接时选择集合,相当于表
------------------------------------------------------------------------------------------------------------------------------------
//数据库连接字符串
string strconn = "mongodb://123.232.119.17:27017/";
//数据库名称
string dbName = "cnblogs";
MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs
MongoDatabase db = server.GetDatabase(dbName);
-------------------------------------------------------------------------------------------------------------------------------------
public void Insert()
{
//创建数据库链接
MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs
MongoDatabase db = server.GetDatabase(dbName);
Users users = new Users();
users.Name = "xumingxiang";
users.Sex = "man";
//获得Users集合,如果数据库中没有,先新建一个
MongoCollection col = db.GetCollection("Users");
//执行插入操作
col.Insert<Users>(users);
}
--------------------------------------------------------------------------------------------------------------------------------------
更新数据
public void Update()
{
//创建数据库链接
MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs
MongoDatabase db = server.GetDatabase(dbName);
//获取Users集合
MongoCollection col = db.GetCollection("Users");
//定义获取“Name”值为“xumingxiang”的查询条件
var query = new QueryDocument { { "Name", "xumingxiang" } };
//定义更新文档
var update = new UpdateDocument { { "$set", new QueryDocument { { "Sex", "wowen" } } } };
//执行更新操作
col.Update(query, update);
}
---------------------------------------------------------------------------------------------------------------------------------------
删除数据
public void Delete()
{
//创建数据库链接
MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs
MongoDatabase db = server.GetDatabase(dbName);
//获取Users集合
MongoCollection col = db.GetCollection("Users");
//定义获取“Name”值为“xumingxiang”的查询条件
var query = new QueryDocument { { "Name", "xumingxiang" } };
//执行删除操作
col.Remove(query);
}
----------------------------------------------------------------------------------------------------------------------------------------
查询数据
public void Query()
{
//创建数据库链接
MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs
MongoDatabase db = server.GetDatabase(dbName);
//获取Users集合
MongoCollection col = db.GetCollection("Users");
//定义获取“Name”值为“xumingxiang”的查询条件
var query = new QueryDocument { { "Name", "xumingxiang" } };
//查询全部集合里的数据
var result1 = col.FindAllAs<Users>();
//查询指定查询条件的第一条数据,查询条件可缺省。
var result2 = col.FindOneAs<Users>();
//查询指定查询条件的全部数据
var result3 = col.FindAs<Users>(query);
}
-------------------------------------------------------------------------------------------------------------------------------------------