简体   繁体   中英

> 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". Now, I am trying to write a query using c# to delete all the records that are 12 months older than the current date.

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. it would be best if you store the dates as ISODate in the db.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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