[英]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.