MongoDB.Driver.Builders如何分组并获得平均值

我们正在使用C#MongoDB驱动程序,我们希望对时间戳的日期部分进行分组,并获得该日期的平均值。 问题是我们无法使用构建器为组找到正确的synthax。

此代码显示了如何使用BSON文档创建组,但我们发现synthax不清楚阅读并且非常令人困惑! 所以正在寻找正确的构建器synthax。

我们想使用Builders,因为它更多地用C#键入,然后在管道中使用带有BsonDocuments的方法。 这是一个代码片段,其中前3个操作有效,但我们无法找到GroupBy。

DateTime from = new DateTime(2014, 12, 2); DateTime to = new DateTime(2014, 12, 4); var id = "37d163c0-44cc-4907-94cf-1e26b5eec911"; var grp = new BsonDocument { { //Sort the documents into groups "$group", new BsonDocument { //Make the unique identifier for the group a BSON element consisting // of a field named Car. // Set its value to that of the Cars field // The Cars field is nolonger an array because it has now been unwound //{ "_id", new BsonDocument { { "Date", "$Date" } } }, { "_id",new BsonDocument{ new BsonDocument("year",new BsonDocument ("$year","$Date")), new BsonDocument("month",new BsonDocument ("$month","$Date")), new BsonDocument("day",new BsonDocument ("$dayOfMonth","$Date")) } }, { //Add a field named Owners "avgAmount", new BsonDocument { { "$avg" ,"$Value"} } } } } }; AggregateArgs aggregateArgs = new AggregateArgs() { Pipeline = new[] { new BsonDocument("$match", Query.EQ(c => c.SensorId, id).ToBsonDocument()) , new BsonDocument("$match", Query.LTE(c => c.Date, to).ToBsonDocument()) , new BsonDocument("$match", Query.GTE(c => c.Date, from).ToBsonDocument()) , grp //, new BsonDocument("$group",GroupBy.Keys(c=> c.Date).ToBsonDocument()) } }; IEnumerable documents = collection.Aggregate(aggregateArgs); 

感谢所有帮助,我们已经在论坛上查看了类似的问题,但找不到正确的工作解决方案, 问题1或问题2 。

使用新的MongoDB .NET驱动程序(2.0 – http://docs.mongodb.org/ecosystem/drivers/csharp/),Linq支持完全支持,这里是使用新驱动程序的问题的synthax。 在使用BsonDocument synthax之前,更加可读的.NET代码。

  public async Task> GetLast31DaysReport(string id) { var mc = new MongoClient(_url); var db = mc.GetDatabase(DbName); var collection = db.GetCollection(CollectionName); DateTime from = DateTime.Now.AddDays(-31); DateTime to = DateTime.Now; var output = await collection.Aggregate() .Match(r => r.SensorId == id) .Match(r => r.Date <= to) .Match(r => r.Date >= to.AddDays(-31)) .Group(r => new { groupedYear = r.Date.Year, groupedMonth = r.Date.Month, groupedDay = r.Date.Day }, g => new { Key = g.Key, avgValue = g.Average(x => x.Value), minValue = g.Min(x => x.Value), maxValue = g.Max(x => x.Value) }) .Project(r => new DailyStat() { Day = r.Key.groupedDay, Month = r.Key.groupedMonth, Year = r.Key.groupedYear, Value = r.avgValue, MinValue = r.minValue, MaxValue = r.maxValue }) .ToListAsync().ConfigureAwait(false); var returnList = new List(); while (returnList.Count < 31) { var value = output.FirstOrDefault(rec => rec.Day == from.Day && rec.Month == from.Month && rec.Year == from.Year); returnList.Add(value ?? new DailyStat() { Month = from.Month, Year = from.Year, Day = from.Day, Value = 0, MaxValue = 0, MinValue = 0 }); from = from.AddDays(1); } return returnList; }