Reputation: 41
I am using MongoDB and C# 4.0. In MongoDB I store CreatedOn as a DateTime, for example "2011-01-01T01:40:45.041Z". In C# I am using MongoDB drivers, so how can I query the database for a particular day? So far i have done as below...
var fileLogCollection = db.GetCollection<FileLog>();
Document selector = new Document();
selector["CreatedOn"] =dateTimePicker1.Value.Date;
var all = fileLogCollection.Find(selector);
Thanks
Upvotes: 4
Views: 6771
Reputation: 90
I am using the following method to query the database. You could have a try.
var date = DateTime.Parse("2012-12-12");
var docs = _docs.asQueryable().Where(o=>o.CreatedOn >= date && o.CreatedOn < date.AddDays(1));
Upvotes: 4
Reputation: 12187
Your sample code doesn't look like it's using the official C# driver.
Using the official C# driver you would write something like:
var collection = database.GetCollection<FileLog>("logs");
var query = Query.EQ("CreatedOn", dateTimePicker1.Value.Date.ToUniversalTime());
foreach (var document in collection.FindAll(query)) {
// process document
}
You also need to make sure you are storing your CreatedOn values as real BSON DateTime values and not as strings.
You also need to keep in mind that DateTime values are stored in UTC with millisecond resolution.
Upvotes: 8