简体   繁体   English

> 或 < 使用 C# 驱动程序在 Mongo db 中存储为字符串的日期时间字段上的运算符

[英]> or< operator on datetime field stored as string in Mongo db using C# driver

I have a collection in Mongo db in which every document has a field date inserted in format "mm/dd/year hrs:min".我在 Mongo db 中有一个集合,其中每个文档都有一个以“mm/dd/year hrs:min”格式插入的字段日期。 Now, I am trying to write a query using c# to delete all the records that are 12 months older than the current date.现在,我正在尝试使用 c# 编写查询,以删除比当前日期早 12 个月的所有记录。

I am using something like this我正在使用这样的东西

deliveryHistory.DeleteMany(x => Convert.ToDateTime(x.DateInserted) < DateTime.Now.AddMonths(-12)); 

which throws the error of to datetime not supported.这会引发不支持的日期时间错误。

you can do it with the following delete command.您可以使用以下删除命令来完成。 i'm afraid there is no strongly typed way to do it with the C# driver though.恐怕没有强类型的方法可以使用 C# 驱动程序来做到这一点。 it would be best if you store the dates as ISODate in the db.最好将日期存储为数据库中的ISODate

await collection.DeleteManyAsync(@"
{
    $expr: {
        $gt: [
            {
                $subtract: [
                    new Date(),
                    {
                        $dateFromString: {
                            dateString: '$DateInserted',
                            format: '%m/%d/%Y %H:%M'
                        }
                    }
                ]
            },
            31540000000
        ]
    }
}");

note: 31540000000 is the number of milliseconds in a year注意:31540000000 是一年中的毫秒数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM