MongoDB如何在一个集合中订购其文档? [英] How does MongoDB order their docs in one collection?

查看:43
本文介绍了MongoDB如何在一个集合中订购其文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 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?

推荐答案

它称为

natural order

数据库引用磁盘上文档的顺序.这是默认的排序顺序.请参见 $natural

natural order

The order in which the database refers to documents on disk. This is the default sort order. See $natural and Return 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 排序的查询

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屋!

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