MongoDB-C# 驱动之增删改查
MongoDB.Driver是MongoDB为C#提供的一种MongoDB数据库操作驱动,利用MongoDB.Driver 我们可以完成对MongoDB常用的增删改查。对于MongoDB的下载及安装部署,大家可以参见:https://www.mongodb.org/downloads 。在安装且部署好 MongoDB之后,我们便可以使用Nuget 获取MongoDB驱动。
新建一个控制台程序,名为MongoDriverSample :
使用 Nuget 程序包管理控制台,键入 Install-Package MongoDB.Driver 来为我们的程序安装 MongoDB 驱动
新建一个 LogInfo 的类文件:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
namespace MongoDriverSample
{
public partial class AppLog
{
[BsonId]
public ObjectId Id { get; set; }
public string Url { get; set; }
public string Result { get; set; }
public string ErrorMsg { get; set; }
public DateTime AddDate { get; set; }
public string Unme { get; set; }
}
}
在MongoDB中创建一个数据库:TestDB, 创建一个Collection, 名为 AppLog(可以名称不必要对应,可以通过后期配置映射,暂时可以设置全部一致) 。这里我的Mongodb部署在 linux服务器上,我使用SSH连接, 键入以下命令:
cd mongo
cd bin
若当前位于mongo/bin 目录下,上两句命令省略
mongo 127.0.0.1:27017
这个地址与端口视具体情况而定
use TestDB
db.createCollection('AppLog')
下面使用C#驱动操作数据库:
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Configuration;
using System.Linq;
namespace MongoDriverSample
{
class Program
{
static string connectionString = ConfigurationManager.ConnectionStrings["mongo"].ConnectionString;
static string databaseName = ConfigurationManager.AppSettings["mongodb"];
static void Main(string[] args)
{
var mongoClient = new MongoClient(connectionString);
var mongoDb = mongoClient.GetDatabase(databaseName);
//查询所有
var filter = new BsonDocument();
Action getAllAction = async () =>
{
var result = await mongoDb.GetCollection<AppLog>("AppLog").Find(filter).ToListAsync();
//这里我就不写了,结果已经转化为 List了
Console.WriteLine(result.Count());
};
getAllAction();
//按条件查询 所有操作人Unme 为 cigarette 的数据
filter = new BsonDocument("Unme", "cigarette");
Action findByParamsAction = async () =>
{
var result = await mongoDb.GetCollection<AppLog>("AppLog").Find(filter).ToListAsync();
Console.WriteLine(result.Count());
};
findByParamsAction();
//新增一条记录
Action insertAction = async () =>
{
await mongoDb.GetCollection<AppLog>("AppLog").InsertOneAsync(new AppLog
{
Url = "http://www.google.com",
Result = "200",
ErrorMsg = "",
AddDate = DateTime.Now,
Unme = "cigarette"
});
};
insertAction();
//修改
Action updateAction = async () =>
{
var result = await mongoDb.GetCollection<AppLog>("AppLog").UpdateOneAsync(
x => x.Unme == "cigarette",
Builders<AppLog>.Update.Set(x => x.Unme, "Cigarette"));
Console.WriteLine(result.ModifiedCount);
};
updateAction();
//删除
Action deleteAction = async () =>
{
var result = await mongoDb.GetCollection<AppLog>("AppLog").DeleteManyAsync(
x => x.Unme == "Cigarette");
Console.WriteLine(result.DeletedCount);
};
deleteAction();
Console.ReadKey();
}
}
}
在这里注意一下:我使用的驱动版本为2.0, MongoDB版本为3.0,由于我使用了异步操作,然而 Main 上是不允许使用async 关键字的,所以在这里使用了Action来封装一个无返回值的方法, 使用async来修饰,这样就可以在方法体中使用 await 关键字来完成异步操作,当然, 一般我们通常并不会去使用控制台程序了,所以我们大可不管,了解即可,下面我们看看数据库中的数据,键入以下命令:
db.AppLog.find().pretty()
pretty() 函数可以让返回的文档排版,可以显示的更加清晰:
testrs:PRIMARY> db.AppLog.find().pretty()
{
"_id" : ObjectId("55ad0430fa119e2368f92046"),
"Url" : "http://www.google.com",
"Result" : "200",
"ErrorMsg" : "",
"AddDate" : ISODate("2015-07-20T14:22:40.633Z"),
"Unme" : "cigarette"
}
{
"_id" : ObjectId("55ad0435fa119e09ac0e56e0"),
"Url" : "http://www.google.com",
"Result" : "200",
"ErrorMsg" : "",
"AddDate" : ISODate("2015-07-20T14:22:44.981Z"),
"Unme" : "cigarette"
}
以上只是使用 C# MongoDB驱动对 MongoDB的基本操作, 后续会使用驱动来写 Web 程序的日志以及缓存等功能。