0

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

Community
  • 1
  • 1
Adrian Lopez
  • 2,601
  • 5
  • 31
  • 48
  • Basically in a similar type of way. To understand the code, this is extracting the "timestamp value'" ( in seconds, not milliseconds, therefore omitted ) and converting to a hex string. That hex string is then padded to the full length of the `ObjectId` ( 12 btyes hex ) and fed to the `ObjectId` constructor for the given language. A fairly simple concept. – Blakes Seven Feb 01 '16 at 02:44

1 Answers1

3

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)));
Adrian Lopez
  • 2,601
  • 5
  • 31
  • 48