Question

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()
            }
        }
    }
}
);
Was it helpful?

Solution

As the MongoDB shell is a JavaScript shell, you need to use the JavaScript Date object:

db.datetest.insert({"event": "New Year's Day 2011", "date": new Date(2011, 0, 1)});
db.datetest.insert({"event": "Now", "date": new Date()});

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:

db.datetest.insert({"event": "Christmas Day 2010", "date": new Date('12/25/2010')});

Be sure to use new Date() rather than just Date(), because Date() 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top