MongoDB: range queries on insertion time with _id

2019-06-14 04:56发布

问题:

I am trying to use mongodb's ObjectID to do a range query on the insertion time of a given collection. I can't really find any documentation that this is possible, except for this blog entry: http://mongotips.com/b/a-few-objectid-tricks/ .

I want to fetch all documents created after a given timestamp. Using the nodejs driver, this is what I have:

var timeId = ObjectId.createFromTime(timestamp);
var query = {
    localUser: userId,
    _id: {$gte: timeId}
};
var cursor = collection.find(query).sort({_id: 1});

I always get the same amount of records (19 in a collection of 27), independent of the timestamp. I noticed that createFromTime only fills the bytes in the objectid related to time, the other ones are left at 0 (like this: 4f6198be0000000000000000).

The reason that I try to use an ObjectID for this, is that I need the timestamp when inserting the document on the mongodb server, not when passing the document to the mongodb driver in node.

Anyone knows how to make this work, or has another idea how to generate and query insertion times that were generated on the mongodb server?

回答1:

Not sure about nodejs driver in ruby, you can simply apply range queries like this.

jan_id = BSON::ObjectId.from_time(Time.utc(2012, 1, 1))       

feb_id = BSON::ObjectId.from_time(Time.utc(2012, 2, 1)) 

@users.find({'_id' => {'$gte' => jan_id, '$lt' => feb_id}})

make sure var timeId = ObjectId.createFromTime(timestamp) is creating an ObjectId.

Also try query without localuser



标签: mongodb range