当前位置:   article > 正文

MongoDB .NET Driver Group By Time Range 按时间分组查询

MongoDB .NET Driver Group By Time Range 按时间分组查询

先看下一个错误的写法:

  1. var filter = Builders<Model>.Filter.Where(r => r.Timestamp > startDate && r.Timestamp < endDate);
  2. var result = Collection.Aggregate()
  3. .Match(filter)
  4. .Group(
  5. r => r.Timestamp.Minute,
  6. g => new
  7. {
  8. ReceiveDate = g.Select(x => x.Timestamp).First(),
  9. Count = g.Count(),
  10. }
  11. ).ToEnumerable();

错误原因:Minute分钟数在跨小时会重复,导致数据错误。

正确的写法:

  1. DateTime startDate = new DateTime(2018, 5, 1, 0, 0, 0, DateTimeKind.Utc);
  2. DateTime endDate = new DateTime(2018, 6, 1, 0, 0, 0, DateTimeKind.Utc);
  3. var result = Collection.Aggregate()
  4. .Match(k => k.Timestamp >= startDate && k.Timestamp < endDate)
  5. .Group(k =>
  6. new DateTime(k.Timestamp.Year, k.Timestamp.Month, k.Timestamp.Day,
  7. k.Timestamp.Hour, k.Timestamp.Minute - (k.Timestamp.Minute % 15), 0),
  8. g => new { _id = g.Key, count = g.Count() }
  9. )
  10. .SortBy(d => d._id)
  11. .ToList();

原文:

https://devpress.csdn.net/mongodb/62fc85617e6682346618fef7.html?

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/152639
推荐阅读
相关标签
  

闽ICP备14008679号