'Casting an object within a MongoDB document to date time within a filter definition builder
I am hoping someone can help me as I am new to Mongo DB or point me to a work around, I have a property within a Mongo DB document which is of type object, but it is a date time, and I would like to be able to filter it by a Lte and Gte filter. The below example is a simplified example, but I cannot change the type in the database, I need to figure out how to on the filter cast the object to Date time so it can be compared with another.
public class Happy
{
public ObjectId Id { get; set; }
public object DateStr { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var db = new MongoClient("mongodb://127.0.0.1:27017").GetDatabase("Test");
var dbCollection = db.GetCollection<Happy>(nameof(Happy));
dbCollection.InsertOne(new Happy { DateStr = DateTime.Now.ToString(CultureInfo.InvariantCulture) });
dbCollection.InsertOne(new Happy { DateStr = DateTime.Now.ToString(CultureInfo.InvariantCulture) });
var test = dbCollection.FindAsync(Builders<Happy>.Filter.Lte(x => (DateTime)x.DateStr, DateTime.Now)).Result.ToList();
}
}
Solution 1:[1]
I would suggest storing the Datetime as "DateTime.Now.ToUniversalTime()"
and then query it like this
Builders<Model>.Filter.Lte(x => (DateTime)x.DateStr, DateTime.Now.AddDays(1));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | JM007 |