MongoDB 如何在一个集合中排序他们的文档? [英] How does MongoDB order their docs in one collection?
问题描述
在我的用户集合中,MongoDB 通常按照我创建它们的相同顺序对每个新文档进行排序:最后创建的文档是集合中的最后一个文档.但是我检测到另一个集合,其中我创建的最后一个集合在 27 个文档之间有 6 个位置.
In my User collection, MongoDB usually orders each new doc in the same order I create them: the last one created is the last one in the collection. But I have detected another collection where the last one I created has the 6 position between 27 docs.
这是为什么?
MongoDB 集合中每个文档的顺序是什么?
Which order follows each doc in MongoDB collection?
推荐答案
它叫做 自然顺序:
数据库引用磁盘上文档的顺序.这是默认的排序顺序.请参阅$natural
和 按自然顺序返回
.
natural order
The order in which the database refers to documents on disk. This is the default sort order. See
$natural
andReturn in Natural Order
.
这证实了通常您会按照插入的顺序获得它们,但这并不能保证——正如您所注意到的.
This confirms that in general you get them in the same order you inserted, but that's not guaranteed–as you noticed.
$natural
参数根据其自然顺序返回项目数据库.此排序是一个内部实现功能,您不应依赖其中的任何特定结构.
Return in Natural Order
The
$natural
parameter returns items according to their natural order within the database. This ordering is an internal implementation feature, and you should not rely on any particular structure within it.
包含按 $natural 排序的查询
命令不要不使用索引来实现查询谓词,但以下例外:如果查询谓词是 _id
字段上的相等条件 <代码>{_id:<值>},然后按<排序查询code>$natural 命令可以使用_id
索引.
Queries that include a sort by $natural
order do not use indexes to fulfill the query predicate with the following exception: If the query predicate is an equality condition on the _id
field { _id: <value> }
, then the query with the sort by $natural
order can use the _id
index.
通常,自然顺序反映插入顺序,但 MMAPv1 存储引擎除外.对于 MMAPv1 存储引擎,如果文档因为 文档增长 或删除操作释放空间,然后被新插入的文档占用.
Typically, the natural order reflects insertion order with the following exception for the MMAPv1 storage engine. For the MMAPv1 storage engine, the natural order does not reflect insertion order if the documents relocate because of document growth or remove operations free up space which are then taken up by newly inserted documents.
显然,就像提到的文档一样,您应该不依赖此默认顺序(此顺序是一个内部实现功能,您不应该依赖其中的任何特定结构.).
Obviously, like the docs mentioned, you should not rely on this default order (This ordering is an internal implementation feature, and you should not rely on any particular structure within it.).
如果您需要对事物进行排序,请使用排序解决方案.
If you need to sort the things, use the sort solutions.
基本上,以下两个调用应该以相同的顺序返回文档(因为默认顺序是 $natural
):
Basically, the following two calls should return documents in the same order (since the default order is $natural
):
db.mycollection.find().sort({ "$natural": 1 })
db.mycollection.find()
如果您想按其他字段(例如 name
)排序,您可以这样做:
If you want to sort by another field (e.g. name
) you can do that:
db.mycollection.find().sort({ "name": 1 })
这篇关于MongoDB 如何在一个集合中排序他们的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!