MongoDB .NET Driver Group By Time Range 按时间分组查询
先看下一个错误的写法:
var filter = Builders<Model>.Filter.Where(r => r.Timestamp > startDate && r.Timestamp < endDate); var result = Collection.Aggregate() .Match(filter) .Group( r => r.Timestamp.Minute, g => new { ReceiveDate = g.Select(x => x.Timestamp).First(), Count = g.Count(), } ).ToEnumerable();
错误原因:Minute分钟数在跨小时会重复,导致数据错误。
正确的写法:
DateTime startDate = new DateTime(2018, 5, 1, 0, 0, 0, DateTimeKind.Utc); DateTime endDate = new DateTime(2018, 6, 1, 0, 0, 0, DateTimeKind.Utc); var result = Collection.Aggregate() .Match(k => k.Timestamp >= startDate && k.Timestamp < endDate) .Group(k => new DateTime(k.Timestamp.Year, k.Timestamp.Month, k.Timestamp.Day, k.Timestamp.Hour, k.Timestamp.Minute - (k.Timestamp.Minute % 15), 0), g => new { _id = g.Key, count = g.Count() } ) .SortBy(d => d._id) .ToList();
原文:
https://devpress.csdn.net/mongodb/62fc85617e6682346618fef7.html?
作者:沐雪
文章均系作者原创或翻译,如有错误不妥之处,欢迎各位批评指正。本文版权归作者和博客园共有,如需转载恳请注明。
如果您觉得阅读这篇博客让你有所收获,请点击右下方【推荐】
为之网-热爱软件编程 http://www.weizhi.cc/