MongoDB .NET 驱动程序 - 将字符串转换为日期时间并用于过滤器生成器
var builder = Builders<ModelClass>.Filter;
var filter = builder.Where(x => x.Active);
if (fromDate.HasValue)
{
var date = fromDate.Value;
var subfilter = builder.Where(x => DateTime.Parse(x.EnrollmentDate) >= date);
filter &= subfilter;
}
注册日期保存为字符串:
public string EnrollmentDate { get; set; }
,我需要过滤一组日期范围内的文档,但如何比较?我需要这样过滤。
我明白了
System.InvalidOperationException:不支持 Parse({document}{EnrollmentDate})。
subfilter
行出错。
var builder = Builders<ModelClass>.Filter;
var filter = builder.Where(x => x.Active);
if (fromDate.HasValue)
{
var date = fromDate.Value;
var subfilter = builder.Where(x => DateTime.Parse(x.EnrollmentDate) >= date);
filter &= subfilter;
}
Enrollment Date is saved as a string:
public string EnrollmentDate { get; set; }
, I need to filter docs within a set of date range, but how do I compare this? I need to filter like this.
I get
System.InvalidOperationException: Parse({document}{EnrollmentDate}) is not supported.
Error in subfilter
line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您需要使用 MongoDB 查询来实现,如下所示:
虽然我认为使用 MongoDB .Net 驱动程序 LINQ 语法无法实现,但您可以将查询转换为
BsonDocument
:I think you need to achieve with MongoDB query as below:
While I think it is not achievable with MongoDB .Net Driver LINQ syntax, you convert the query as
BsonDocument
:当您想要执行
DateTime.Parse()
时,您会遇到问题。您可以发布字符串
EnrollmentDate
的格式吗?你的变量date
,只是 Date 还是 DateTime ?这个也许可以帮助你这里
另外,尝试使用
You have problem here when you want to do
DateTime.Parse()
Can you post format of your string
EnrollmentDate
? And your variabledate
, is it only Date or DateTime?This one maybe can help you here
Also, try to use
我在 MongoDB 中的 DateTime 解析时遇到了同样的错误,因此我建议您将模型中的 EnrollmentDate 重构为 DateTime。 MongoDB 知道如何保留 DateTime 以及如何根据它进行过滤和排序,而无需更改子过滤器。
I had the same error with DateTime parsing in MongoDB so I'd suggest you to refactor EnrollmentDate in your model to DateTime. MongoDB knows how to persist DateTime and how to Filter and Sort by it without having to change your subfilters.