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

使用MongoDB.Driver在C#中按日期筛选无法找到文档问题

解决MongoDB.Driver精确匹配DateTime返回0结果的问题

你遇到的问题本质是MongoDB中存储的DateEnd字段包含毫秒部分,而你构造的docDate没有毫秒,导致表面显示值相同但实际底层数值不相等。C#调试时显示DateTime会自动隐藏末尾的0毫秒,但MongoDB存储时会保留原始的毫秒精度,因此精确相等匹配会失败。

解决方案1:使用秒级范围匹配(最简单直接)

把范围查询缩小到秒级,实现近似精确匹配:

var exact = mongodb.Find<CubeDataModel>(x => x.DateEnd >= docDate && x.DateEnd < docDate.AddSeconds(1)).ToList();

解决方案2:修改模型,限制DateTime序列化精度

在CubeDataModel的DateEnd属性上添加BsonDateTimeOptions特性,指定存储时只保留秒级精度,让插入和查询的DateTime精度统一:

public class CubeDataModel
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string _id { get; set; }
    // 其他字段...
    [BsonDateTimeOptions(Kind = DateTimeKind.Utc, Precision = DateTimePrecision.Second)]
    public DateTime DateEnd { get; set; }
    // 其他字段...
}

注:修改特性后,需通过脚本更新现有文档的DateEnd字段,截断毫秒以统一精度。

解决方案3:构造查询时截断毫秒

使用BsonDateTime截断目标时间的毫秒部分,确保查询值与存储值精度一致:

var targetDate = BsonDateTime.Create(docDate).Truncate(TimeSpan.FromSeconds(1));
var filter = Builders<CubeDataModel>.Filter.Eq(x => x.DateEnd, targetDate);
var exact = mongodb.Find(filter).ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:42:55