MongoDB: range queries on insertion time with _id and ObjectID

三世轮回 提交于 2020-01-03 05:07:07

问题


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



来源:https://stackoverflow.com/questions/11192136/mongodb-range-queries-on-insertion-time-with-id-and-objectid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!