28

I have a collection that looks like this:

{
  _id: ObjectId("50a68673476427844b000001"),
  other fields
}

I want to do a range query to find records between two dates. I know that I can get the date from the ObjectId in the mongo shell var doing this:

var aDate = ObjectId().getTimestamp()

but there isn't a way (as far as I can figure out at the moment) to create an ObjectId consisting of just the timestamp portion - I think my ideal solution is non-functioning mongo shell code would be:

var minDate = ObjectId(new Date("2012-11-10"));
var maxDate = ObjectId(new Date("2012-11-17"));

Use the find with the minDate and MaxDate as the range values.

Is there a way to do this in the SHELL - I'm not interested in some of the driver products.

4

2 回答 2

33

您可以分两步完成:

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

或一步(可读性较差):

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")}})
于 2012-11-27T22:33:49.637 回答
25

使用 mongo 外壳:

您可以使用 ObjectId.fromDate 内置方法:

db.mycollection.find({_id: {$gt: ObjectId.fromDate( new Date('2017-09-23') ) } });

从 Node.js 驱动程序:

您可以在此处使用@jksdua 提供的解决方案,如下所示:

db.mycollection.find({_id: {$gt: ObjectID.createFromTime( Date.now()/1000 ) } });
于 2017-09-23T10:41:08.897 回答