thewayman
thewayman

Reputation: 41

Mongodb C# filter by datetime property

I am looking for way to filter a date time field in mongodb. It seems very straight forward but I am unable to find any documentation regarding this on there site or with google search.

Bson Document

{
   "_id" : ObjectId("560cd175c771472d780aab3c"),
   "BDay" : ISODate("2005-12-22T18:00:00.000Z"),
   "AddressID" : 987,
   "Age" : 58,
   "Father" : {
       "BDay" : {
         "_csharpnull" : true
       },
       "AddressID" : 0,
       "Age" : 31,
       "Father" : null,
       "ID" : "6e2a9c3b-091a-4171-843e-6cbd0994bfda",
       "Income" : 26794.0000000000000000,
       "Name" : "YLM66LF3",
       "_id" : ObjectId("000000000000000000000000")
   },
   "ID" : "707080e6-8705-48b1-8471-f7af58be6d11",
   "Income" : 5734.0000000000000000,
   "Name" : "XVCDFKF8"
}

My Code is given below.

    var collection = cdb.GetCollection<BsonDocument>("person");
    var bday= new DateTime(2015, 12, 22, 18, 00, 00).ToLocalTime();
    var s = BsonValue.Create(beginTime);
    var filter = Builders<BsonDocument>.Filter.Gte("BDay", s);
    var result = await collection.Find(filter).ToListAsync();

I have tried other method but all have been unsuccessful.

Upvotes: 2

Views: 6362

Answers (1)

jhmt
jhmt

Reputation: 1421

According to the API Document, the paremeters of Filter.Gte method is FieldDefinition<TDocument, TField>, TField.
As FieldDefinition<TDocument, TField> is an abstract class so there should be a subclass of this.
My example of Gte queries is like this:
(Assuming your beginTime is DateTime value)

var filter = Builders<BsonDocument>.Filter.Gte(new StringFieldDefinition<BsonDocument, BsonDateTime>("BDay"), new BsonDateTime(beginTime)); 

Upvotes: 1

Related Questions