Search code examples
c#mongodbdatedrivermongodb-.net-driver

Filter by date using an idObject


Hí, this mongoDB query, filter documents by date using an idObject field.

db.myCollection.find({_id:{$gt: ObjectId(Math.floor((new Date('1990/10/10'))/1000).toString(16) + "000
0000000000000"), $lt: ObjectId(Math.floor((new Date('2011/10/10'))/1000).toString(16) + "000
0000000000000")}})

How would you implement this using the C# driver? There's already any method to convert a date to idObject?

Reference post: https://stackoverflow.com/a/13594408/2010764


Solution

  • One of the developers of the driver, told me about a very interesting constructor. I hope this will be useful to someone in the future:

    // Get all documents created today.
    var query = Query.And(
        Query.GTE("_id", new ObjectId (DateTime.UtcNow.Date,0,0,0)),
        Query.LT ("_id", new ObjectId (DateTime.UtcNow.Date.AddDays(1),0,0,0)));