我有一个字段类型为 DateTime
的类:
class Model {
public DateTime Date { get; set; }
}
在 mongo 数据库中,它存储为:
“日期”:“2018-02-01T13:22:08Z”
代码:
var builder = Builders<Model>.Filter;
var filter = builder.In("Date", new[]
{
"2018-02-01T13:22:08Z"
});
// Returns zero element list
_collection.Find(filter).ToList();
有趣的是:
var workingFilter = new BsonDocument()
{
{ "Date", "2018-02-01T13:22:08Z"}
};
// This one actually works
_collection.Find(workingFilter).ToList();
当我提供 string
作为 DateTime
字段的值进行查询时,我认为 Mongo 的 Builder
实用程序有问题。
最佳答案
首先,您的 .NET DateTime
存储为 MongoDB string
,这不是默认行为。默认情况下,您应该能够在数据库中看到类似这样的内容:
"Date" : ISODate("2018-02-01T13:22:08Z")
因此,数据库中存储的类型与模型中的类型不匹配。请记住,MongoDB 在检查值之前检查类型,并且不存在类似于 JavaScript 的隐式转换。
在您的工作示例中,您使用了 BsonDocument
handles dynamic documents所以驱动程序简单地忽略了模型中指定的数据类型并将其转换为
db.yourCollection.find({"Date" : "2018-02-01T13:22:08Z"})
并返回该文档。
第二个代码片段使用通用的 Filter
Builder
因此您指定您关心 Model
类中的类型。
您可以在级别 2 上启用 MongoDB 探查器,然后运行您的 .NET 代码:
db.setProfilingLevel(2)
然后您可以在您的数据库上运行以下查询:
db.system.profile.find({ns: "yourdb.yourcollection"}).sort({ts:-1}).limit(1).pretty()
您将看到驱动程序生成的查询:
"command" : {
"find" : "yourcollection",
"filter" : {
"Date" : {
"$in" : [
ISODate("2018-02-01T13:22:08Z")
]
}
},
"$db" : "yourdb"
}
如您所见,驱动程序知道 DateTime
并将您的字符串转换为 ISODate
,这会导致数据库查询级别的类型不匹配,这就是您得不到结果的原因.
解决方案?要么将您的 .NET DateTime
存储为 MongoDB 中的 ISODate
(推荐),要么始终使用 BsonDocument
构建您的查询。
关于c# - Mongo Builder 将 `String` 用于 `DateTime` 类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52102793/