MongoDB:使用_id和ObjectID对插入时间进行范围查询 [英] MongoDB: range queries on insertion time with _id and ObjectID

查看:595
本文介绍了MongoDB:使用_id和ObjectID对插入时间进行范围查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mongodb的ObjectID对给定集合的插入时间进行范围查询.除了此博客条目,我真的找不到任何可能的文档: http ://mongotips.com/b/a-few-objectid-tricks/.

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/ .

我想获取在给定时间戳记之后创建的所有文档.使用nodejs驱动程序,这就是我所拥有的:

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});

我总是得到相同数量的记录(27个集合中的19个),与时间戳无关.我注意到createFromTime仅填充了与时间相关的objectid中的字节,其他的则保留为0(例如:4f6198be0000000000000000).

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).

之所以尝试使用ObjectID,是因为在mongodb服务器上插入文档时需要时间戳,而不是在将文档传递给节点中的mongodb驱动程序时需要时间戳.

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.

任何人都知道如何进行这项工作,或者有另一个想法如何生成和查询在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?

推荐答案

不确定ruby中的nodejs驱动程序,您可以像这样简单地应用范围查询.

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}})

确保 var timeId = ObjectId.createFromTime(timestamp)正在创建一个ObjectId.

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

也可以尝试在没有localuser的情况下进行查询

Also try query without localuser

这篇关于MongoDB:使用_id和ObjectID对插入时间进行范围查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆