Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Query MongoDB date time in C#?

Tags:

mongodb

c#-4.0

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

like image 904
user1125435 Avatar asked Dec 16 '22 05:12

user1125435


1 Answers

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.

like image 174
Robert Stam Avatar answered Jan 01 '23 17:01

Robert Stam