繁体   English   中英

在 MongoDB 5.0、c# 驱动程序中过滤基于时间的数据:得到错误(零)结果

[英]filtering timebased data in MongoDB 5.0, c# driver: getting wrong (zero) results

我有一个用 MongoDB5.0 引入的 TimeSeries 集合,里面装满了大约 100000 个文档,并希望过滤器工作,例如获取集合内特定时间范围的文档计数。

// Timestamp must be a BSON date (as the doc's say), which is BSONDateTime in c#
// so the time range boundaries for the filter is based on the BSon Default 1/1/1970
// from, to are TimeSpan objects

var dt1 = new DateTime(1970,1,1,0,0,0, DateTimeKind.Utc) + from;
var dt2= new DateTime(1970,1,1,0,0,0, DateTimeKind.Utc) + to;

var filter = Builders<MongoTimeSeriesDocument>.Filter.Gte(x => x.Timestamp, dt1);
filter &= Builders<MongoTimeSeriesDocument>.Filter.Lte(x => x.Timestamp, dt2);

// result: zero
var docCount = await collection.CountDocumentsAsync(filter)
                .ConfigureAwait(false);
// result: zero
var docCount2 = await collection.Find(filter)
                .CountDocumentsAsync()
                .ConfigureAwait(false);

我还注册了一个 DateTimeSeriealizer:

BsonSerializer.RegisterSerializer(typeof(DateTime), new DateTimeSerializer(DateTimeKind.Utc));

序列化程序不起作用。

这有效:

// result: 70000
var docCount = await collection.CountDocumentsAsync(x => x.Timestamp < new DateTime(2021,11,7,0,0,0, DateTimeKind.Utc))
                .ConfigureAwait(false);

虽然这不起作用(它应该算全部,因为时间戳 > 1970):

// result: 0
var docCount2 = await collection.CountDocumentsAsync(x => x.Timestamp > new DateTime(1970,1,1,0,0,0, DateTimeKind.Utc))
                .ConfigureAwait(false);
// same with BsonDateTime: result: 0
var docCount2 = await collection.CountDocumentsAsync(x => x.Timestamp > new BsonDateTime(new DateTime(1970,1,1,0,0,0, DateTimeKind.Utc)))
                .ConfigureAwait(false);

在 C# 中,我采用 Bson 方式并传递一个$match字符串,该字符串有 2 个表示$gte$lte表达式。 这适用于 TimeSeries:

var filterStage = new StringBuilder();
            filterStage.Append("{$match:{$and:[ {$expr: {$gte:");
            filterStage.Append("[ \"$Timestamp\",");
            filterStage.Append($"ISODate('{isoFrom}'),");
            filterStage.Append("]}}, {$expr:{ $lte:");
            filterStage.Append("[ \"$Timestamp\",");
            filterStage.Append($"ISODate('{isoTo}')");
            filterStage.Append("]}} ]}}");

            var aggregation = await collection.Aggregate()
                .AppendStage<MongoTimeSeriesDocument>(filterStage.ToString())
                .ToListAsync()
                .ConfigureAwait(false);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM