简体   繁体   English

MongoDB:使用_id和ObjectID对插入时间进行范围查询

[英]MongoDB: range queries on insertion time with _id and ObjectID

I am trying to use mongodb's ObjectID to do a range query on the insertion time of a given collection. 我正在尝试使用mongodb的ObjectID对给定集合的插入时间进行范围查询。 I can't really find any documentation that this is possible, except for this blog entry: http://mongotips.com/b/a-few-objectid-tricks/ . 除了以下博客条目,我真的找不到任何可能的文档: 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: 使用nodejs驱动程序,这就是我所拥有的:

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. 我总是得到相同数量的记录(27个集合中的19个),与时间戳无关。 I noticed that createFromTime only fills the bytes in the objectid related to time, the other ones are left at 0 (like this: 4f6198be0000000000000000). 我注意到createFromTime只填充与时间相关的objectid中的字节,其他的则保留为0(例如: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. 我尝试为此使用ObjectID的原因是,在mongodb服务器上插入文档时需要时间戳,而不是在将文档传递给节点中的mongodb驱动程序时需要时间戳。

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? 任何人都知道如何进行这项工作,或者有另一个想法如何生成和查询在mongodb服务器上生成的插入时间?

Not sure about nodejs driver in ruby, you can simply apply range queries like this. 不确定ruby中的nodejs驱动程序,您可以像这样简单地应用范围查询。

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. 确保var timeId = ObjectId.createFromTime(timestamp)正在创建ObjectId。

Also try query without localuser 也尝试在没有localuser的情况下进行查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM