You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB自定义时间差过滤查询报错,寻求解决方案

问题原因

MongoDB的LINQ驱动无法将你写的(DateTime.UtcNow - s.BilledDateTime.Value).TotalMilliseconds这个客户端计算表达式转换成MongoDB能执行的查询语句,因此抛出了序列化信息无法确定的异常。驱动仅支持可映射到MongoDB原生操作符的表达式,这种复杂的客户端计算不在支持范围内。

修复后的代码
var builder = Builders<T>.Filter;
// 提前计算10秒前的UTC时间作为阈值
var threshold = DateTime.UtcNow.AddMilliseconds(-10000);
var filter = builder.Where(t => t.Status == 1);
// 直接比较BilledDateTime是否早于等于阈值(与原时间差≥10000毫秒逻辑等价)
filter &= builder.Lte(s => s.BilledDateTime.Value, threshold);
return await Collection.Find(filter).ToListAsync();
逻辑说明

原需求是筛选当前时间与BilledDateTime的时间差≥10000毫秒的文档,这个逻辑完全等价于BilledDateTime≤当前时间减去10000毫秒。把计算逻辑移到客户端提前完成后,查询就变成了简单的字段值比较,驱动能顺利将其翻译为MongoDB的$lte操作符查询,自然不会再触发异常。

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 09:32:40