How to request MongoDB time in C #?

I am using MongoDB and C # 4.0. In MongoDB, I stored CreateOn as a DateTime, for example, "2011-01-01T01: 40: 45.041Z". In C #, I use MongoDB drivers, so how can I query a database for a specific day? So far I have done as shown below ...

var fileLogCollection = db.GetCollection<FileLog>(); Document selector = new Document(); selector["CreatedOn"] =dateTimePicker1.Value.Date; var all = fileLogCollection.Find(selector); 

thanks

+4
source share
2 answers

Your sample code is not like it using the official C # driver.

Using the official C # driver, you should 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 that you save the CreateOn values ​​as real BSON DateTime values, not as strings.

You also need to keep in mind that DateTime values ​​are stored in UTC with a resolution in milliseconds.

+8
source

I use the following method to query the database. You can try.

 var date = DateTime.Parse("2012-12-12"); var docs = _docs.asQueryable().Where(o=>o.CreatedOn >= date && o.CreatedOn < date.AddDays(1)); 
+4
source

Source: https://habr.com/ru/post/1388848/


All Articles