I am using the MongoDB-Csharp driver and I was wondering what the proper way to insert and query date field?
I tried using storing the dates using System.DateTime, but I am having issues when I try to query by date.
example:
Inserting Data
var mongo = new Mongo();
var db = mongo.GetDatabase(dbName);
var collection = db.GetCollection(collectionName);
var document = new Document();
document["date"] = DateTime.Now.ToUniversalTime();
collection.Save(document);
Querying Data
var mongo = new Mongo();
var db = mongo.GetDatabase(dbName);
var collection = db.GetCollection(collectionName);
var results = collection.Find(
new Document()
{
{
"date",
new Document()
{
{
"$lte", DateTime.Now.ToUniversalTime()
}
}
}
}
);
As the MongoDB shell is a JavaScript shell, you need to use the JavaScript Date object:
Note that if you pass year, month, date to the constructor the months start at 0.
You can also pass a string to its constructor but it seems to ignore the locale so your date needs to be formatted US-style:
Be sure to use
new Date()rather than justDate(), becauseDate()just returns a string and you won’t be able to query it as a Date.The MongoDB-CSharp driver will convert the .NET DateTime object into a MongoDB Date object when it serializes it to BSON.