先看下一个错误的写法:
- 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?