MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

How can I use date string in c# driver builder?

in c# driver builder is not working and i want to keep date in string only in json. pls suggest.
{
“ProgressDate” : “2019-01-01”
}
var filter1 = Builders.Filter.Where(w => w[“ProgressDate”]==Convert.ToDateTime(“2019-01-01”));

yours sincerley

Hi @Rajesh_Yadav,

Just to clarify, you have documents in a collection with field ProgressDate that stores value in DateTime, and you would like to query using a string format of date given only yyyy-mm-dd i.e. 2019-01-01 ?

If so, you can convert using DateTime.Parse() method. For example:

var stringDate = "2019-01-01";
DateTime dateFilter = DateTime.Parse(stringDate, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal );
var filterDefinition = Builders<Test>.Filter.Where(t => t.ProgressDate==dateFilter);

Please note that MongoDB stores time in UTC by default. This is the DateTimeStyles.AssumeUniversal param option is for. If you intend to convert the string date from local time to UTC just replaced with DateTimeStyles.AdjustToUniversal. See more info System.Globalization.

If this doesn’t answer your question, please provide the following information so that others can help you better:

  • MongoDB .NET/C# driver version
  • Elaborate more on “not working”, i.e. do you get an error ? Is it not returning what you want ? if so, what do you expect it to return ?
  • An example document in the collection

Regards,
Wan.

1 Like

it is not getting the record , that means it is not filltering.
version i have used is 1.10.2
and json i have given u which i have kept in mongodb.
and finlly the quey is also given by me.
result is i must get the json i have entered in mondogdb. in c# var filter1

If that’s the case, the field value is string you don’t need to call Convert.ToDateTime() and just use string to query it. i.e.

var stringDate = "2019-01-01";
var filterDefinition = Builders<Test>.Filter.Where(t => t.ProgressDate==stringDate);

Regards,
Wan.

this one is also not working
var filter = Builders.Filter.Where(w=> w[“ProgressDate”] <= “2019-01-01”);

i wanted to use <= insted of ===
like following.

var stringDate = “2019-01-01”;
var filterDefinition = Builders.Filter.Where(t => t.ProgressDate <= stringDate)

–other thing is u can use bsondocument also in place of Test , if that works i will take that one also.