_id上的mongodb排序顺序 [英] mongodb sort order on _id

查看:1412
本文介绍了_id上的mongodb排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道mongodb在执行如下查询时如何比较"_id"字段:

I wonder how mongodb compare the "_id" field when doing query like the following:

db.data.find({"_id":{$gt:ObjectId("502aa46c0674d23e3cee6152")}}).sort({"_id":1}).limit(10);

它是纯粹基于id的时间戳部分吗?

Is it purely based on timestamp portion of the id?

推荐答案

对安德烈所说的内容稍作扩充:

To expand slightly on what Andre said:

由于ObjectID时间戳仅为第二个,因此可以轻松地创建两个(或更多)具有相同时间戳记值(前4个字节)的ObjectID.如果这些是在同一台机器(机器ID-接下来的3个字节)上通过同一进程(PID-接下来的2个字节)创建的,则唯一区分它们的就是"inc"字段,最后3个字节最后.

Since the ObjectID timestamp is only to the second, two (or more) ObjectIDs could easily be created with the same value for the timestamp (the first 4 bytes). If these were created on the same machine (machine ID - the next 3 bytes), by the same process (PID - the next 2 bytes), then the only thing to differentiate them would be the "inc" field, the last 3 bytes at the end.

更新:2020年1月

此答案仍然很受欢迎,因此值得进行一些更新.自从8年前编写此答案以来,ObjectID规范已经得到了发展,现在时间戳之后的5个字节现在只是随机的,这将大大降低发生任何冲突的可能性.最后三个字节仍是增量的,但是被初始化为随机值以开始,从而再次降低了冲突的可能性.现在,ObjectID包含的上下文较少(您无法轻易分辨出它是在哪里生成的以及由哪个进程生成),但是我猜想该信息并未以任何有意义的方式被使用,并且已被弃用,以便更好地对ID进行随机化.

This answer continues to be popular so it is worth updating a little. The ObjectID spec has evolved since this answer was written 8 years ago and the 5 bytes after the timestamp are now simply random, which will greatly decrease the likelihood of any collisions. The last three bytes are still incremental, but initialised at a random value to start, again making collisions less likely. The ObjectID now contains less context (you can't easily tell where it was generated and by what process) but I would guess that the information was not being used in any meaningful way and has been deprecated in favor of better randomisation of the ID.

结束更新

有关完整规格,请参见此处:

See here for the full spec:

https://docs.mongodb.com/manual/reference/method/ObjectId/#ObjectIDs-BSONObjectIDSpecification

该"inc"字段可以是一个不断增加的字段(然后您可以合理地期望排序按插入/创建顺序)或一个随机值(然后可能是唯一的,但没有排序),并假设已实现规范当然是正确的.请注意,ObjectID可能是由驱动程序或应用程序生成的(或者实际上是手动生成的),而不是由MongoDB本身生成的,因此,除非您完全控制它们的生成方式,否则上述任何一项或全部均可适用.

That "inc" field is either an ever incrementing field (then you can reasonably expect the sort to be in the insert/create order) or a random value (then likely unique, but not ordered), assuming the spec is implemented correctly of course. Note that the ObjectIDs may be generated by the driver, or the application (or indeed manually) rather than by MongoDB itself, so unless you have full control over how they are generated, then any or all of the above may apply.

这篇关于_id上的mongodb排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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