MongoDB C#为什么不能将DateTime.Date与IQueryable一起使用?

我在MongoDB DAL类中设置了方法.

public IQueryable<MyModel> Retrieve(Expression<Func<MyModel, bool>> expression) 
{
    if (!BsonClassMap.IsClassMapRegistered(typeof(MyModel)))
    {
        DoMapping();
    }

    var client = new MongoClient(MongoConnectionString);
    var database = client.GetDatabase("DatabaseName");
    var documents = database.GetCollection<MyModel>("MyModelTable");

    return documents.AsQueryable<MyModel>().Where(expression);
}

我想做一些简单的事情

var result = Retrieve(a => a.someDateProperty.Date >= startDate && a.someDateProperty.Date <= endDate);

但是,每次尝试时,都会显示错误消息:

An exception of
type ‘system.invalidOperationException’ occurred in MongoDB.Driver.dll
but was not handled in user code

Additional information: {document}{SomeDateProperty}.Date is not
supported.

我正在使用官方的C#驱动程序版本2.2.4.26.

有没有办法只查询日期?我已经看到了有关使用DbFunctions.Truncate的帖子,但是那是在EntityFramework库中,我希望远离.

解决方法:

我在使用Date时遇到了同样的问题,我使用了:

想法是使用两个边框(DateTime.Date也是DateTime,但带有0小时0分钟…,第二个是第二天,也带有0小时0分钟…).

DateTime currentDayStart = DateTime.Now.Date;
DateTime currentDayEnds  = DateTime.Now.Date.AddDays(1);

var result = Retrieve(a => a.someDateProperty >= currentDayStart && a.someDateProperty < currentDayEnds);

它对我来说很好.

相关文章

MongoTemplate 是Spring Data MongoDB 中的一个核心类,为 S...
笔者今天要分享的是一个项目重构过程中如何将数据库选型由原...
mongodb/mongoTemplate.upsert批量插入更新数据的实现
进入官网下载官网安装点击next勾选同意,点击next点击custom...
头歌 MongoDB实验——数据库基本操作
期末考试复习总结