ShadowMonkey
ShadowMonkey

Reputation: 13

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();
    }
}

Upvotes: 0

Views: 486

Answers (1)

JM007
JM007

Reputation: 26

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));

Upvotes: 1

Related Questions