使用的驱动是官方最新驱动2.2.4
首先写一个帮助类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using MongoDB.Bson;
using MongoDB.Driver;
namespace WebMongo.NewClass
{
public class MongoHelp
{
public static readonly string connectionString = ConfigurationManager.ConnectionStrings["MongoConnString"].ConnectionString;
public IMongoCollection
{
var client = new MongoClient(connectionString);
var data = client.GetDatabase(connectionString);
var mycollection = data.GetCollection
return mycollection;
}
}
}
然后在这个的基础上进行一些操作,简单的curd就不写了,这写一些查询的操作。如下:
MongoHelp _mongo = new MongoHelp(); //实例化一个帮助对象
IMongoCollection
var filterBuilder = Builders
var query= filterBuilder.Eq("EngineID",EngineID) & filterBuilder.Eq("SiteID", siteID) & filterBuilder.Gte("DateTime", beinghourtime) & filterBuilder.Lte("DateTime", endhourtime);
var find = collection.Aggregate().Match(query).Group(new BsonDocument { { "_id", "" }, { "Count", new BsonDocument("$sum", 1) }, { "VisitorsCount",new BsonDocument("$sum", "$VisitorsCount") } });
var list = find.ToList();
上面的代码要注意:一时间格式要转变BsonDateTime
BsonDateTime beinghourtime = BsonDateTime.Create(DateTime.Parse(beginDate.ToString("yyyy-MM-dd") ));
二 query 是相当于sql的where过滤条件,
三 collection.Aggregate().Match(filter)执行过滤条件
四 Group 是分组查询
五 BsonDocument 的格式要注意确保写对。
下面是根据年月日分组,和 EngineID分组 查询的代码:
var query= filterBuilder.Eq("SiteID", siteID) & filterBuilder.Gte("DateTime", beinghourtime) & filterBuilder.Lte("DateTime", endhourtime);
var find = collection.Aggregate().Match(query).Group(new BsonDocument{{"_id",new BsonDocument{ new BsonDocument("Month",new BsonDocument("$month","$DateTime")) , new BsonDocument("Day", new BsonDocument("$dayOfMonth", "$DateTime")), new BsonDocument("Year", new BsonDocument("$year", "$DateTime")), new BsonDocument("EngineID", "$EngineID") }},
{"IP",new BsonDocument("$sum","$IP")},{"Visitors",new BsonDocument("$sum","$Visitors")},{"NewVisitors",new BsonDocument("$sum","$NewVisitors")}});
sort() 函数是 order by 作用相同,project(),查询的列,这里就不在一一写例子了。
可以参考:https://docs.mongodb.com/manual/reference/operator/aggregation/group/
和 http://www.tuicool.com/articles/2iqUZj