MongoDB如何在一个集合中订购其文档? [英] How does MongoDB order their docs in one collection?
问题描述
在我的 User 集合中,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?
推荐答案
它称为
数据库引用磁盘上文档的顺序.这是默认的排序顺序.请参见 The order in which the database refers to documents on disk. This is the default sort order. See 这可以确认,通常您会以插入时的顺序获得它们,但是并不能保证–如您所注意到的那样. This confirms that in general you get them in the same order you inserted, but that's not guaranteed–as you noticed. The 包含按 Queries that include a sort by 通常,自然顺序反映插入顺序,但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. 基本上,以下两个调用应以相同的顺序返回文档(因为默认顺序为 Basically, the following two calls should return documents in the same order (since the default order is 如果要按其他字段(例如 If you want to sort by another field (e.g. 这篇关于MongoDB如何在一个集合中订购其文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
natural order
$natural
和
natural order
$natural
and Return in Natural Order
.
自然订单退货
Return in Natural Order
$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
排序的查询$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.$natural
):$natural
):db.mycollection.find().sort({ "$natural": 1 })
db.mycollection.find()
name
)排序,可以执行以下操作:name
) you can do that:db.mycollection.find().sort({ "name": 1 })