简体   繁体   中英

How to filter by a TimeSpan field stored as string using mongodb c# driver?

I have a mongodb collection with a field that stores time in string format. In my C# code, the model has a property of type TimeStamp:

public TimeSpan StartTime { get; set; }

I need a query to get all documents where StartTime is greater than UtcNow. Something like:

var now = new TimeSpan(DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Second);
...
...
var docs = db.GetCollection<DocDataModel>("docs")
             .AsQueryable()
             .Where(e => e.StartTime > now)

But I get an InvalidOperationException with message: Where(({document}{StartTime} > 12:04:52))) is not supported.

Is there any way to write this query properly?

Convert the StartTime and now variable to long using TimeSpan.Ticks

var now = new TimeSpan(DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Second).Ticks;
...
...
var docs = db.GetCollection<DocDataModel>("docs")
             .AsQueryable()
             .Where(e => e.StartTime.Ticks > now)

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