namespace MongoGroupDemo
{
class Program
{
private static string MongoConnStr = "mongodb://172.16.86.53:27017";
/// <summary>
/// MongoDB Group,max仿关系型数据库例子
/// 需求:锯齿状数据表,取所有用户最近一天的数据
///
///
static void Main(string[] args)
{
InitData();
// 取最近一天的数据
Dictionary dic = new Dictionary();
dic["_userName"] = ""; // 与原字段名区分开
dic["_date"] = "";
dic["_data"] = "0";
MongoServer server = new MongoClient(MongoConnStr).GetServer();
MongoDatabase db = server.GetDatabase("admin");
var docs = db.GetCollection("GroupDemo").Group(null, new GroupByBuilder(new string[] { "userName" }),
BsonDocument.Create(dic),
BsonJavaScript.Create("function(obj,prev){if(prev._date < obj.date){prev._userName=obj.userName; prev._date=obj.date; prev._data=obj.data;}}"),
BsonJavaScript.Create("function(obj){ obj.userName=obj._userName; obj.date=obj._date; obj.data=obj._data; delete obj._userName; delete obj._date;delete obj._data; }")).ToList();
if (docs != null)
{
foreach (var doc in docs)
Console.WriteLine(doc);
}
}
///
/// 初始化缓存数据
///
private static void InitData()
{
try
{
MongoServer server = new MongoClient(MongoConnStr).GetServer();
MongoDatabase db = server.GetDatabase("admin");
// 初始化
if (db.CollectionExists("GroupDemo"))
db.GetCollection("GroupDemo").Drop();
db.GetCollection("GroupDemo").Save(CreateBsonDoc("u1", new DateTime(2015, 7, 20), 100));
db.GetCollection("GroupDemo").Save(CreateBsonDoc("u1", new DateTime(2015, 7, 22), 200));
db.GetCollection("GroupDemo").Save(CreateBsonDoc("u2", new DateTime(2015, 5, 22), 100));
db.GetCollection("GroupDemo").Save(CreateBsonDoc("u2", new DateTime(2015, 6, 22), 200));
db.GetCollection("GroupDemo").Save(CreateBsonDoc("u2", new DateTime(2015, 7, 23), 300));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private static BsonDocument CreateBsonDoc(string userName, DateTime date, decimal data)
{
BsonDocument doc = new BsonDocument();
doc.Add("_id", Guid.NewGuid().ToString("N"));
doc.Add("userName", userName);
doc.Add("date", date);
doc.Add("data", (double)data);
return doc;
}
}
}
运行结果:
{ "userName" : "u1", "date" : ISODate("2015-07-21T16:00:00Z"), "data" : 200.0 }
{ "userName" : "u2", "date" : ISODate("2015-07-22T16:00:00Z"), "data" : 300.0 }
完整的工程(vs 2012)代码点此下载。
更多的Group聚合相关资料请查看官方文档。