MongoDB Limits and ThresholdsMongoDB限制和阈值
On this page本页内容
This document provides a collection of hard and soft limitations of the MongoDB system.本文档提供了MongoDB系统的硬限制和软限制的集合。
BSON DocumentsBSON文件
BSON Document SizeBSON文档大小-
The maximum BSON document size is 16 megabytes.BSON文档的最大大小为16兆字节。The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth.最大文档大小有助于确保单个文档不会使用过多的RAM,或者在传输过程中不会使用过大的带宽。To store documents larger than the maximum size, MongoDB provides the GridFS API. See为了存储大于最大大小的文档,MongoDB提供了GridFS API。有关GridFS的更多信息,请参阅mongofiles
and the documentation for your driver for more information about GridFS.mongofiles
和驱动程序的文档。
Nested Depth for BSON DocumentsBSON文档的嵌套深度-
MongoDB supports no more than 100 levels of nesting for BSON documents.MongoDB支持BSON文档的嵌套级别不超过100个。Each object or array adds a level.每个对象或数组都会添加一个级别。
Naming Restrictions命名限制
Use of Case in Database Names数据库名称中大小写的使用-
Do not rely on case to distinguish between databases.不要依赖案例来区分数据库。For example, you cannot use two databases with names like,例如,不能使用名称为salesData
andSalesData
.salesData
和SalesData
的两个数据库。After you create a database in MongoDB, you must use consistent capitalization when you refer to it.在MongoDB中创建数据库后,在引用数据库时必须使用一致的大写字母。For example, if you create the例如,如果创建salesData
database, do not refer to it using alternate capitalization such assalesdata
orSalesData
.salesData
数据库,请不要使用salesdata
或salesData
等其他大写字母引用它。
Restrictions on Database Names for WindowsWindows数据库名称的限制-
For MongoDB deployments running on Windows, database names cannot contain any of the following characters:对于在Windows上运行的MongoDB部署,数据库名称不能包含以下任何字符:/\. "$*<>:|?
Also database names cannot contain the null character.此外,数据库名称不能包含null
字符。
Restrictions on Database Names for Unix and Linux SystemsUnix和Linux系统的数据库名称限制-
For MongoDB deployments running on Unix and Linux systems, database names cannot contain any of the following characters:对于在Unix和Linux系统上运行的MongoDB部署,数据库名称不能包含以下任何字符:/\. "$
Also database names cannot contain the null character.此外,数据库名称不能包含null
字符。
Length of Database Names数据库名称的长度-
Database names cannot be empty and must have fewer than 64 characters.数据库名称不能为空,并且必须少于64个字符。
Restriction on Collection Names集合名称限制-
Collection names should begin with an underscore or a letter character, and cannot:集合名称应以下划线或字母字符开头,并且不能:contain the包含$
.$
。be an empty string (e.g.是一个空字符串(例如""
).""
)。contain the null character.包含null
字符。begin with the从system.
prefix. (Reserved for internal use.)system.
前缀开始(保留供内部使用。)
If your collection name includes special characters, such as the underscore character, or begins with numbers, then to access the collection use the如果集合名称包含特殊字符,如下划线或以数字开头,则要访问集合,请使用db.getCollection()
method inmongosh
or a similar method for your driver.mongosh
中的db.getCollection()
方法或驱动程序的类似方法。Namespace Length:命名空间长度:For对于设置为“4.4”或更高版本的featureCompatibilityVersion
set to"4.4"
or greater, MongoDB raises the limit for unsharded collections and views to 255 bytes, and to 235 bytes for sharded collections.featureCompatibilityVersion
,MongoDB将未排序集合和视图的限制提高到255字节,将分片集合的限制提高至235字节。For a collection or a view, the namespace includes the database name, the dot (对于集合或视图,名称空间包括数据库名称、句点(.
) separator, and the collection/view name (e.g.<database>.<collection>
),.
)分隔符和集合/视图名称(例如<database>.<collection>
),For对于设置为“4.2”或更早版本的featureCompatibilityVersion
set to"4.2"
or earlier, the maximum length of unsharded collections and views namespace remains 120 bytes and 100 bytes for sharded collection.featureCompatibilityVersion
,未排序集合和视图命名空间的最大长度保持为120字节,而对于分片集合,则保持为100字节。
Restrictions on Field Names字段名称的限制-
Field names cannot contain the字段名称不能包含null
character.null
字符。The server permits storage of field names that contain dots (服务器允许存储包含点(.
) and dollar signs ($
)..
)和美元符号($
)的字段名。MongodB 5.0 adds improved support for the use of (MongodB 5.0增加了对字段名称中使用($
) and (.
) in field names.$
)和(.
)的改进支持。There are some restrictions. See Field Name Considerations for more details.有一些限制。有关更多详细信息,请参阅字段名称注意事项。
Restrictions on _id对_id
的限制-
The field name字段名称_id
is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array._id
被保留用作主键;它的值在集合中必须是唯一的,是不可变的,并且可以是数组以外的任何类型。If the如果_id
contains subfields, the subfield names cannot begin with a ($
) symbol._id
包含子字段,则子字段名称不能以($
)符号开头。
Naming Warnings命名警告
Use caution, the issues discussed in this section could lead to data loss or corruption.请注意,本节中讨论的问题可能会导致数据丢失或损坏。
MongoDB does not support duplicate field namesMongoDB不支持重复的字段名
The MongoDB Query Language is undefined over documents with duplicate field names. MongoDB查询语言对于字段名称重复的文档是未定义的。BSON builders may support creating a BSON document with duplicate field names. BSON构建器可能支持创建具有重复字段名称的BSON文档。While the BSON builder may not throw an error, inserting these documents into MongoDB is not supported even if the insert succeeds. 虽然BSON构建器可能不会抛出错误,但即使插入成功,也不支持将这些文档插入MongoDB。For example, inserting a BSON document with duplicate field names through a MongoDB driver may result in the driver silently dropping the duplicate values prior to insertion.例如,通过MongoDB驱动程序插入具有重复字段名称的BSON文档可能会导致驱动程序在插入之前静默地丢弃重复的值。
Import and Export Concerns With Dollar Signs ($
) and Periods (.
)美元符号($
)和点号(.
)的导入导出问题
$
) and Periods (.
)Starting in MongoDB 5.0, document field names can be dollar (从MongoDB 5.0开始,文档字段名称可以是美元($
) prefixed and can contain periods (.
). However, mongoimport
and mongoexport
may not work as expected in some situations with field names that make use of these characters.$
)前缀,并且可以包含句点(.
)。但是,对于使用这些字符的字段名,mongoimport
和mongoexport
在某些情况下可能无法正常工作。
MongoDB Extended JSON v2 cannot differentiate between type wrappers and fields that happen to have the same name as type wrappers. MongoDB Extended JSON v2无法区分类型包装器和碰巧与类型包装器同名的字段。Do not use Extended JSON formats in contexts where the corresponding BSON representations might include dollar (在相应的BSON表示可能包括以美元($
) prefixed keys. $
)为前缀的键的上下文中,不要使用扩展JSON格式。The DBRef mechanism is an exception to this general rule.DBRef机制是这个一般规则的一个例外。
There are also restrictions on using 在字段名称中使用带句点(mongoimport
and mongoexport
with periods (.
) in field names. .
)的mongoimport
和mongoexport
也有限制。Since CSV files use the period (由于CSV文件使用句点(.
) to represent data hierarchies, a period (.
) in a field name will be misinterpreted as a level of nesting..
)表示数据层次结构,因此字段名称中的句点(.
)将被误解为嵌套级别。
Possible Data Loss With Dollar Signs ($
) and Periods (.
)美元符号($
)和句点(.
)可能的数据丢失
$
) and Periods (.
)There is a small chance of data loss when using dollar (在MongoDB 5.0以前的服务器上,如果使用以美元($
) prefixed field names or field names that contain periods (.
) if these field names are used in conjunction with unacknowledged writes (write concern w=0
) on servers that are older than MongoDB 5.0.$
)为前缀的字段名或包含句点(.
)的字段名与未确认的写入(写入关注w=0
)一起使用,则数据丢失的可能性很小。
When running 当运行insert
, update
, and findAndModify
commands, drivers that are 5.0 compatible remove restrictions on using documents with field names that are dollar ($
) prefixed or that contain periods (.
). insert
、update
和findAndModify
命令时,与5.0兼容的驱动程序将删除对使用字段名称以美元($
)为前缀或包含句点(.
)的文档的限制。These field names generated a client-side error in earlier driver versions.这些字段名称在早期的驱动程序版本中生成了客户端错误。
The restrictions are removed regardless of the server version the driver is connected to. 无论驱动程序连接到哪个服务器版本,都会删除这些限制。If a 5.0 driver sends a document to an older server, the document will be rejected without sending an error.如果5.0驱动程序将文档发送到较旧的服务器,则该文档将被拒绝而不会发送错误。
Namespaces命名空间
Namespace Length命名空间长度-
For对于设置为“4.4”或更高版本的featureCompatibilityVersion
set to"4.4"
or greater, MongoDB raises the limit for unsharded collections and views to 255 bytes, and to 235 bytes for sharded collections.featureCompatibilityVersion
,MongoDB将未排序集合和视图的限制提高到255字节,将分片集合的限制提高至235字节。For a collection or a view, the namespace includes the database name, the dot (对于集合或视图,名称空间包括数据库名称、句点(.
) separator, and the collection/view name (e.g.<database>.<collection>
),.
)分隔符和集合/视图名称(例如<database>.<collection>
),For对于设置为“4.2”或更早版本的featureCompatibilityVersion
set to"4.2"
or earlier, the maximum length of unsharded collections and views namespace remains 120 bytes and 100 bytes for sharded collection.featureCompatibilityVersion
,未排序集合和视图命名空间的最大长度保持为120字节,而对于分片集合,则保持为100字节。
TipSee also:另请参阅:
Indexes索引
Index Key Limit索引键限制- Note
Changed in version 4.2在版本4.2中更改Starting in version 4.2, MongoDB removes the Index Key Limit for从4.2版本开始,MongoDB删除了featureCompatibilityVersion
(fCV) set to"4.2"
or greater.featureCompatibilityVersion
(fCV)设置为“4.2”或更高版本的索引键限制。For MongoDB 2.6 through MongoDB versions with fCV set to对于fCV设置为“4.0”或更早版本的MongoDB 2.6到MongoDB版本,索引项的总大小必须小于1024字节,根据BSON类型,索引项可能包括结构开销。"4.0"
or earlier, the total size of an index entry, which can include structural overhead depending on the BSON type, must be less than 1024 bytes.When the Index Key Limit applies:当应用索引键限制时:MongoDB will not create an index on a collection if the index entry for an existing document exceeds the index key limit.如果现有文档的索引项超过索引键限制,MongoDB将不会在集合上创建索引。Reindexing operations will error if the index entry for an indexed field exceeds the index key limit. Reindexing operations occur as part of the如果索引字段的索引项超过索引键限制,则重新索引操作将出错。重新索引操作是compact
command as well as thedb.collection.reIndex()
method.compact
命令和db.collection.reIndex()
方法的一部分。Because these operations drop all the indexes from a collection and then recreate them sequentially, the error from the index key limit prevents these operations from rebuilding any remaining indexes for the collection.由于这些操作会从集合中删除所有索引,然后按顺序重新创建它们,因此索引键限制的错误会阻止这些操作为集合重新生成任何剩余索引。MongoDB will not insert into an indexed collection any document with an indexed field whose corresponding index entry would exceed the index key limit, and instead, will return an error.MongoDB不会将任何具有索引字段的文档插入到索引集合中,该字段的相应索引条目将超过索引键限制,相反,它将返回一个错误。Previous versions of MongoDB would insert but not index such documents.MongoDB的早期版本会插入但不会索引此类文档。Updates to the indexed field will error if the updated value causes the index entry to exceed the index key limit.如果更新的值导致索引项超过索引键限制,则对索引字段的更新将出错。If an existing document contains an indexed field whose index entry exceeds the limit, any update that results in the relocation of that document on disk will error.如果现有文档包含索引项超过限制的索引字段,则导致该文档在磁盘上重新定位的任何更新都将出错。mongorestore
andmongoimport
will not insert documents that contain an indexed field whose corresponding index entry would exceed the index key limit.mongorestore
和mongoimport
不会插入包含相应索引项超过索引键限制的索引字段的文档。In MongoDB 2.6, secondary members of replica sets will continue to replicate documents with an indexed field whose corresponding index entry exceeds the index key limit on initial sync but will print warnings in the logs.在MongoDB 2.6中,副本集的辅助成员将继续复制具有索引字段的文档,该字段的相应索引条目在初始同步时超过了索引键限制,但会在日志中打印警告。Secondary members also allow index build and rebuild operations on a collection that contains an indexed field whose corresponding index entry exceeds the index key limit but with warnings in the logs.辅助成员还允许对包含索引字段的集合执行索引生成和重新生成操作,该字段的相应索引项超过了索引键限制,但日志中出现警告。With mixed version replica sets where the secondaries are version 2.6 and the primary is version 2.4, secondaries will replicate documents inserted or updated on the 2.4 primary, but will print error messages in the log if the documents contain an indexed field whose corresponding index entry exceeds the index key limit.对于混合版本副本集(其中辅助副本为2.6版,主副本为2.4版),辅助副本将复制在2.4主副本上插入或更新的文档,但如果文档包含相应索引项超过索引键限制的索引字段,则会在日志中打印错误消息。For existing sharded collections, chunk migration will fail if the chunk has a document that contains an indexed field whose index entry exceeds the index key limit.对于现有的分片集合,如果区块的文档包含索引项超过索引键限制的索引字段,则区块迁移将失败。
Number of Indexes per Collection每个集合的索引数-
A single collection can have no more than 64 indexes.一个集合的索引不能超过64个。
Index Name Length索引名称长度- Note
Changed in version 4.2在版本4.2中更改Starting in version 4.2, MongoDB removes the Index Name Length limit for MongoDB versions with从4.2版本开始,MongoDB删除了featureCompatibilityVersion
(fCV) set to"4.2"
or greater.featureCompatibilityVersion
(fCV)设置为“4.2”或更高版本的MongoDB版本的索引名称长度限制。In previous versions of MongoDB or MongoDB versions with fCV set to在MongoDB的早期版本或fCV设置为"4.0"
or earlier, fully qualified index names, which include the namespace and the dot separators (i.e.<database name>.<collection name>.$<index name>
), cannot be longer than 127 bytes."4.0"
或更早版本的MongoDB版本中,包括命名空间和点分隔符(即<database name>.<collection name>.$<index name>
)的完全限定索引名称不能超过127字节。By default,默认情况下,<index name>
is the concatenation of the field names and index type.<index name>
是字段名称和索引类型的串联。You can explicitly specify the您可以显式地为<index name>
to thecreateIndex()
method to ensure that the fully qualified index name does not exceed the limit.createIndex()
方法指定<index name>
,以确保完全限定的索引名称不超过限制。
Number of Indexed Fields in a Compound Index复合索引中的索引字段数-
There can be no more than 32 fields in a compound index.一个复合索引中的字段不能超过32个。
Queries cannot use both text and Geospatial Indexes查询不能同时使用文本索引和地理空间索引-
You cannot combine the不能将需要特殊文本索引的$text
query, which requires a special text index, with a query operator that requires a different type of special index. For example you cannot combine$text
query with the$near
operator.$text
查询与需要不同类型特殊索引的查询运算符组合在一起。例如,不能将$text
查询与$near
运算符组合使用。
Fields with 2dsphere Indexes can only hold Geometries具有2dsphere索引的字段只能包含几何图形-
Fields with 2dsphere indexes must hold geometry data in the form of coordinate pairs or GeoJSON data.具有2dsphere
索引的字段必须以坐标对或GeoJSON数据的形式保存几何数据。If you attempt to insert a document with non-geometry data in a如果尝试在2dsphere
indexed field, or build a2dsphere
index on a collection where the indexed field has non-geometry data, the operation will fail.2dsphere
索引字段中插入包含非几何数据的文档,或者在索引字段包含非几何体数据的集合上构建2dsphere
索引,则操作将失败。TipSee also:另请参阅:The unique indexes limit in Sharding Operational Restrictions.分片操作限制中的唯一索引限制。
Limited Number of 2dsphere index keys2dsphere索引键的数量有限-
To generate keys for a 2dsphere index,为了生成mongod
maps GeoJSON shapes to an internal representation.2dsphere
索引的键,mongod
将GeoJSON形状映射到内部表示。The resulting internal representation may be a large array of values.所得到的内部表示可以是一个大的值数组。When当mongod
generates index keys on a field that holds an array,mongod
generates an index key for each array element.mongod
在包含数组的字段上生成索引键时,mongod
会为每个数组元素生成一个索引键。For compound indexes,对于复合索引,mongod
calculates the cartesian product of the sets of keys that are generated for each field.mongod
计算为每个字段生成的键集的笛卡尔乘积。If both sets are large, then calculating the cartesian product could cause the operation to exceed memory limits.如果两个集合都很大,那么计算笛卡尔乘积可能会导致操作超出内存限制。indexMaxNumGeneratedKeysPerDocument
limits the maximum number of keys generated for a single document to prevent out of memory errors.限制为单个文档生成的最大键数,以防止内存不足错误。The default is 100000 index keys per document.默认值为每个文档100000个索引键。It is possible to raise the limit, but if an operation requires more keys than the可以提高限制,但如果操作需要的键数超过indexMaxNumGeneratedKeysPerDocument
parameter specifies, the operation will fail.indexMaxNumGeneratedKeysPerDocument
参数指定的键数,则操作将失败。
NaN values returned from Covered Queries by the WiredTiger Storage Engine are always of type doubleWiredTiger存储引擎从覆盖查询返回的NaN值始终为double
类型-
If the value of a field returned from a query that is covered by an index is如果从索引所覆盖的查询返回的字段的值为NaN
, the type of thatNaN
value is alwaysdouble
.NaN
,则该NaN
值的类型始终为double
。
Multikey Index多键索引-
Multikey indexes多键索引cannot cover queries over array fields.无法覆盖对数组字段的查询。
Geospatial Index地理空间索引-
Geospatial indexes can't cover a query.地理空间索引无法覆盖查询。
Memory Usage in Index Builds索引构建中的内存使用情况-
createIndexes
supports building one or more indexes on a collection.支持在集合上生成一个或多个索引。createIndexes
uses a combination of memory and temporary files on disk to complete index builds.使用磁盘上的内存和临时文件的组合来完成索引构建。The default limit on memory usage forcreateIndexes
is 200 megabytes (for versions 4.2.3 and later) and 500 (for versions 4.2.2 and earlier), shared between all indexes built using a singlecreateIndexes
command.createIndexes
的内存使用默认限制为200兆字节(适用于4.2.3及更高版本)和500兆字节(用于4.2.2及更早版本),在使用单个createIndexes
命令构建的所有索引之间共享。Once the memory limit is reached,一旦达到内存限制,createIndexes
uses temporary disk files in a subdirectory named_tmp
within the--dbpath
directory to complete the build.createIndexes
就会使用--dbpath
目录中名为_tmp
的子目录中的临时磁盘文件来完成构建。You can override the memory limit by setting the您可以通过设置maxIndexBuildMemoryUsageMegabytes
server parameter.maxIndexBuildMemoryUsageMegabytes
服务器参数来覆盖内存限制。Setting a higher memory limit may result in faster completion of index builds.设置更高的内存限制可能会更快地完成索引构建。However, setting this limit too high relative to the unused RAM on your system can result in memory exhaustion and server shutdown.但是,相对于系统上未使用的RAM,将此限制设置得过高可能会导致内存耗尽和服务器关闭。For feature compatibility version (fcv)对于功能兼容性版本(fcv)“4.2”及更高版本,索引构建内存限制适用于所有索引构建。"4.2"
and later, the index build memory limit applies to all index builds.
Index builds may be initiated either by a user command such as索引构建可以由用户命令(如createIndexes
or by an administrative process such as an initial sync.createIndexes
)启动,也可以由管理过程(如初始同步)启动。Both are subject to the limit set by两者都受maxIndexBuildMemoryUsageMegabytes
.maxIndexBuildMemoryUsageMegabytes
设置的限制。An initial sync populates only one collection at a time and has no risk of exceeding the memory limit.初始同步一次只填充一个集合,并且没有超过内存限制的风险。However, it is possible for a user to start index builds on multiple collections in multiple databases simultaneously and potentially consume an amount of memory greater than the limit set by但是,用户可能同时在多个数据库中的多个集合上启动索引生成,并且可能消耗的内存量大于maxIndexBuildMemoryUsageMegabytes
.maxIndexBuildMemoryUsageMegabytes
设置的限制。TipTo minimize the impact of building an index on replica sets and sharded clusters with replica set shards, use a rolling index build procedure as described on Rolling Index Builds on Replica Sets.要最大限度地减少对副本集和具有副本集分片的分片集群构建索引的影响,请使用滚动索引构建过程,如在副本集上滚动索引构建中所述。
Collation and Index Types排序规则和索引类型-
The following index types only support simple binary comparison and do not support collation:以下索引类型仅支持简单的二进制比较,不支持排序规则:TipTo create a若要在具有非简单排序规则的集合上创建text
or2d
index on a collection that has a non-simple collation, you must explicitly specify{collation: {locale: "simple"} }
when creating the index.text
索引或2d
索引,必须在创建索引时显式指定{collation: {locale: "simple"} }
。
Sorts排序
Data数据
Maximum Number of Documents in a Capped Collection有上限集合中的最大文档数-
If you specify the maximum number of documents in a capped collection with如果使用create
'smax
parameter, the value must be less than 2 31 documents.create
的max
参数指定带上限集合中的最大文档数,则该值必须小于2
31个文档。If you do not specify a maximum number of documents when creating a capped collection, there is no limit on the number of documents.如果在创建上限集合时未指定最大文档数,则文档数没有限制。
Replica Sets复制集
Number of Voting Members of a Replica Set副本集的投票成员数-
Replica sets can have up to 7 voting members.副本集最多可以有7个投票成员。For replica sets with more than 7 total members, see Non-Voting Members.有关总共有7个以上成员的副本集,请参阅无表决权成员。
Maximum Size of Auto-Created Oplog自动创建的操作日志的最大大小-
If you do not explicitly specify an oplog size (i.e. with如果您没有明确指定oplog大小(即使用oplogSizeMB
or--oplogSize
) MongoDB will create an oplog that is no larger than 50 gigabytes.oplogSizeMB
或--oplogSize
),MongoDB将创建一个不超过50 GB的oplog。[1][1] The oplog can grow past its configured size limit to avoid deleting theoplog可以超过其配置的大小限制,以避免删除多数提交点。majority commit point
.
Sharded Clusters分片集群
Sharded clusters have the restrictions and thresholds described here.分片集群具有此处描述的限制和阈值。
Sharding Operational Restrictions分片操作限制
Operations Unavailable in Sharded Environments在分片环境中不可用的操作-
$where
does not permit references to the不允许从db
object from the$where
function.$where
函数引用db
对象。This is uncommon in un-sharded collections.这在未分片的集合中并不常见。The在分片环境中不支持geoSearch
command is not supported in sharded environments.geoSearch
命令。In MongoDB 5.0 and earlier, you cannot specify sharded collections in the在MongoDB 5.0及更早版本中,不能在from
parameter of$lookup
stages.$lookup
阶段的from
参数中指定分片集合。
Covered Queries in Sharded Clusters分片集群中的覆盖查询-
When run on当在mongos
, indexes can only cover queries on sharded collections if the index contains the shard key.mongos
上运行时,如果索引包含分片键,则索引只能覆盖对cover queries on 分片集合的查询。
Sharding Existing Collection Data Size共享现有集合数据大小-
An existing collection can only be sharded if its size does not exceed specific limits.只有当现有集合的大小不超过特定限制时,才能对其进行分片。These limits can be estimated based on the average size of all shard key values, and the configured chunk size.这些限制可以基于所有分片键值的平均大小和配置的块大小来估计。ImportantThese limits only apply for the initial sharding operation. Sharded collections can grow to any size after successfully enabling sharding.这些限制仅适用于初始分片操作。成功启用分片后,分片集合可以增长到任何大小。MongoDB distributes documents in the collection so that each chunk is half full at creation. Use the following formulas to calculate the theoretical maximum collection size.MongoDB在集合中分发文档,这样每个区块在创建时都是半满的。使用以下公式计算理论上的最大集合大小。maxSplits = 16777216 (bytes) / <average size of shard key values in bytes>
maxCollectionSize (MB) = maxSplits * (chunkSize / 2)NoteIf如果maxCollectionSize
is less than or nearly equal to the target collection, increase the chunk size to ensure successful initial sharding.maxCollectionSize
小于或几乎等于目标集合,请增加区块大小以确保成功的初始分片。If there is doubt as to whether the result of the calculation is too 'close' to the target collection size, it is likely better to increase the chunk size.如果对计算结果是否过于“接近”目标集合大小存在疑问,则最好增加块大小。After successful initial sharding, you can reduce the chunk size as needed.在成功的初始分片之后,您可以根据需要减少区块大小。If you later reduce the chunk size, it may take time for all chunks to split to the new size.如果以后减少块大小,则可能需要时间将所有块拆分为新大小。See Modify Range Size in a Sharded Cluster for instructions on modifying chunk size.有关修改区块大小的说明,请参阅修改分片集群中的范围大小。This table illustrates the approximate maximum collection sizes using the formulas described above:此表说明了使用上述公式的近似最大集合大小:Average Size of Shard Key Values分片键值的平均大小512 bytes 256 bytes 128 bytes 64 bytes Maximum Number of Splits最大分割数32,768 65,536 131,072 262,144 Max Collection Size最大集合大小(64 MB Chunk Size)1 TB 2 TB 4 TB 8 TB Max Collection Size最大集合大小(128 MB Chunk Size)2 TB 4 TB 8 TB 16 TB Max Collection Size最大集合大小(256 MB Chunk Size)4 TB 8 TB 16 TB 32 TB
Single Document Modification Operations in Sharded Collections分片集合中的单个文档修改操作-
All指定update
andremove()
operations for a sharded collection that specify thejustOne
ormulti: false
option must include the shard key or the_id
field in the query specification.justOne
或multi:false
选项的分片集合的所有update
和remove()
操作都必须在查询规范中包含分片键或_id
字段。在不包含分片键或update
andremove()
operations specifyingjustOne
ormulti: false
in a sharded collection which do not contain either the shard key or the_id
field return an error._id
字段的分片集合中指定justOne
或multi:false
的update
和remove()
操作返回错误。
Unique Indexes in Sharded Collections分片集合中的唯一索引-
MongoDB does not support unique indexes across shards, except when the unique index contains the full shard key as a prefix of the index.MongoDB不支持跨分片的唯一索引,除非唯一索引包含完整的分片键作为索引的前缀。In these situations MongoDB will enforce uniqueness across the full key, not a single field.在这些情况下,MongoDB将在整个键中强制执行唯一性,而不是单个字段。TipSee:请参阅:Unique Constraints on Arbitrary Fields for an alternate approach.任意字段上的唯一约束以了解替代方法。
Maximum Number of Documents Per Range to Migrate每个范围要迁移的最大文档数-
By default, MongoDB cannot move a range if the number of documents in the range is greater than 2 times the result of dividing the configured range size by the average document size.默认情况下,如果范围中的文档数量大于配置的范围大小除以平均文档大小的结果的2倍,MongoDB将无法移动该范围。If MongoDB can move a sub-range of a chunk and reduce the size to less than that, the balancer does so by migrating a range.如果MongoDB可以移动一个区块的子范围并将大小缩小到小于这个范围,那么均衡器就可以通过迁移一个范围来实现这一点。db.collection.stats()
includes the包括avgObjSize
field, which represents the average document size in the collection.avgObjSize
字段,该字段表示集合中的平均文档大小。For chunks that are too large to migrate:对于太大而无法迁移的块:The balancer setting平衡器设置attemptToBalanceJumboChunks
allows the balancer to migrate chunks too large to move as long as the chunks are not labeled jumbo.attemptToBalanceJumboChunks
允许平衡器迁移太大而无法移动的块,只要这些块没有标记为jumbo
。See Balance Ranges that Exceed Size Limit for details.有关详细信息,请参阅超出大小限制的平衡范围。When issuing在发出moveRange
andmoveChunk
commands, it's possible to specify the forceJumbo option to allow for the migration of ranges that are too large to move.moveRange
和moveChunk
命令时,可以指定forceJumbo
选项以允许迁移太大而无法移动的范围。The ranges may or may not be labeled jumbo.范围可以标记为jumpo
,也可以不标记为jumpo
。
Shard Key Limitations分片键限制
Shard Key Size分片键大小-
Starting in version 4.4, MongoDB removes the limit on the shard key size.从4.4版本开始,MongoDB取消了对分片键大小的限制。For MongoDB 4.2 and earlier, a shard key cannot exceed 512 bytes.对于MongoDB 4.2及更早版本,分片键不能超过512字节。
Shard Key Index Type分片键索引类型-
A shard key index can be an ascending index on the shard key, a compound index that start with the shard key and specify ascending order for the shard key, or a hashed index.分片键索引可以是分片键上的升序索引、以分片键开始并指定分片键升序的复合索引,也可以是哈希索引。A shard key index cannot be an index that specifies a multikey index, a text index or a geospatial index on the shard key fields.分片键索引不能是在分片键字段上指定多键索引、文本索引或地理空间索引的索引。
Shard Key Selection is Immutable in MongoDB 4.2 and EarlierMongoDB 4.2及更早版本中的分片键选择是不可变的-
Your options for changing a shard key depend on the version of MongoDB that you are running:您更改分片键的选项取决于您正在运行的MongoDB版本:Starting in MongoDB 5.0, you can reshard a collection by changing a document's shard key.从MongoDB 5.0开始,您可以通过更改文档的分片键来重新分片集合。Starting in MongoDB 4.4, you can refine a shard key by adding a suffix field or fields to the existing shard key.从MongoDB 4.4开始,您可以通过在现有的分片键中添加一个或多个后缀字段来细化分片键。In MongoDB 4.2 and earlier, the choice of shard key cannot be changed after sharding.在MongoDB 4.2及更早版本中,分片后不能更改对分片键的选择。
In MongoDB 4.2 and earlier, to change a shard key:在MongoDB 4.2及更早版本中,要更改分片键:Dump all data from MongoDB into an external format.将MongoDB中的所有数据转储为外部格式。Drop the original sharded collection.丢弃原始分片集合。Configure sharding using the new shard key.使用新的分片键配置分片。- Pre-split
the shard key range to ensure initial even distribution.分片键范围以确保初始均匀分布。 Restore the dumped data into MongoDB.将转储的数据恢复到MongoDB中。
Monotonically Increasing Shard Keys Can Limit Insert Throughput单调增加分片键会限制插入吞吐量-
For clusters with high insert volumes, a shard key with monotonically increasing and decreasing keys can affect insert throughput.对于具有高插入量的集群,具有单调递增和递减键的分片键可能会影响插入吞吐量。If your shard key is the如果您的分片键是_id
field, be aware that the default values of the_id
fields are ObjectIds which have generally increasing values._id
字段,请注意_id
字段的默认值是ObjectIds,其值通常会增加。When inserting documents with monotonically increasing shard keys, all inserts belong to the same chunk on a single shard.当插入具有单调增加的分片键的文档时,所有插入都属于单个分片上的同一块。The system eventually divides the chunk range that receives all write operations and migrates its contents to distribute data more evenly.系统最终划分接收所有写入操作的区块范围,并迁移其内容以更均匀地分配数据。However, at any moment the cluster directs insert operations only to a single shard, which creates an insert throughput bottleneck.然而,集群在任何时候都只将插入操作定向到单个分片,这会造成插入吞吐量瓶颈。If the operations on the cluster are predominately read operations and updates, this limitation may not affect the cluster.如果集群上的操作主要是读取操作和更新,则此限制可能不会影响集群。To avoid this constraint, use a hashed shard key or select a field that does not increase or decrease monotonically.若要避免此约束,请使用哈希分片键或选择不单调增加或减少的字段。Hashed shard keys and hashed indexes store hashes of keys with ascending values.哈希分片键和哈希索引存储具有升序的键的哈希。
Operations操作
Sort Operations排序操作-
If MongoDB cannot use an index or indexes to obtain the sort order, MongoDB must perform a blocking sort operation on the data.如果MongoDB不能使用一个或多个索引来获得排序顺序,那么MongoDB必须对数据执行阻塞排序操作。The name refers to the requirement that the该名称指的是SORT
stage reads all input documents before returning any output documents, blocking the flow of data for that specific query.SORT
阶段在返回任何输出文档之前读取所有输入文档的要求,从而阻止特定查询的数据流。If MongoDB requires using more than 100 megabytes of system memory for the blocking sort operation, MongoDB returns an error unless the query specifies如果MongoDB需要使用超过100兆字节的系统内存进行阻塞排序操作,则除非查询指定cursor.allowDiskUse()
(New in MongoDB 4.4).cursor.allowDiskUse()
,否则MongoDB将返回错误(MongoDB 4.4中的新增)。allowDiskUse()
allows MongoDB to use temporary files on disk to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation.允许MongoDB在处理阻塞排序操作时使用磁盘上的临时文件来存储超过100兆字节系统内存限制的数据。Changed in version 4.44.4版更改: For MongoDB 4.2 and prior, blocking sort operations could not exceed 32 megabytes of system memory.:对于MongoDB 4.2及以前版本,阻塞排序操作不能超过32兆字节的系统内存。For more information on sorts and index use, see Sort and Index Use.有关排序和索引使用的详细信息,请参阅排序和索引的使用。
Aggregation Pipeline Operation聚合管道操作-
Starting in MongoDB 6.0, the从MongoDB 6.0开始,allowDiskUseByDefault
parameter controls whether pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default.allowDiskUseByDefault
参数控制需要超过100MB内存才能执行的管道阶段是否默认将临时文件写入磁盘。If如果allowDiskUseByDefault
is set totrue
, pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default.allowDiskUseByDefault
设置为true
,则默认情况下,需要超过100兆字节内存才能执行的管道阶段会将临时文件写入磁盘。You can disable writing temporary files to disk for specific您可以使用find
oraggregate
commands using the{ allowDiskUse: false }
option.{ allowDiskUse: false }
选项禁用将临时文件写入磁盘以执行特定的find
或aggregate
命令。If如果allowDiskUseByDefault
is set tofalse
, pipeline stages that require more than 100 megabytes of memory to execute raise an error by default.allowDiskUseByDefault
设置为false
,则需要超过100兆字节内存才能执行的管道阶段在默认情况下会引发错误。You can enable writing temporary files to disk for specific您可以使用find
oraggregate
using the{ allowDiskUse: true }
option.{ allowDiskUse: true }
选项将临时文件写入磁盘以进行特定find
或aggregate
。
The$search
aggregation stage is not restricted to 100 megabytes of RAM because it runs in a separate process.$search
聚合阶段不限于100兆字节的RAM,因为它在一个单独的进程中运行。Examples of stages that can write temporary files to disk when allowDiskUse is当true
are:allowDiskUse
为true
时,可以将临时文件写入磁盘的阶段示例如下:$bucket
$bucketAuto
$group
$setWindowFields
$sort
when the sort operation is not supported by an index当索引不支持排序操作时$sortByCount
NotePipeline stages operate on streams of documents with each pipeline stage taking in documents, processing them, and then outputing the resulting documents.管道阶段对文档流进行操作,每个管道阶段接收文档,对其进行处理,然后输出生成的文档。Some stages can't output any documents until they have processed all incoming documents. These pipeline stages must keep their stage output in RAM until all incoming documents are processed.某些阶段在处理完所有传入文档后才能输出任何文档。这些流水线阶段必须将其阶段输出保存在RAM中,直到处理完所有传入的文档。As a result, these pipeline stages may require more space than the 100 MB limit.因此,这些流水线阶段可能需要比100MB限制更多的空间。If the results of one of your如果某个$sort
pipeline stages exceed the limit, consider adding a $limit stage.$sort
管道阶段的结果超过了限制,请考虑添加一个$limit
阶段。Starting in MongoDB 4.2, the profiler log messages and diagnostic log messages includes a从MongoDB 4.2开始,如果任何聚合阶段由于内存限制将数据写入临时文件,探查器日志消息和诊断日志消息都会包含一个usedDisk
indicator if any aggregation stage wrote data to temporary files due to memory restrictions.usedDisk
指示符。
Aggregation and Read Concern聚合和读取关注-
Starting in MongoDB 4.2, the从MongoDB 4.2开始,$out
stage cannot be used in conjunction with read concern"linearizable"
.$out
阶段不能与读取关注"linearizable"
一起使用。That is, if you specify也就是说,如果为"linearizable"
read concern fordb.collection.aggregate()
, you cannot include the$out
stage in the pipeline.db.collection.aggregate()
指定"linearizable"
读取关注,则不能在管道中包含$out
阶段。The$merge
stage cannot be used in conjunction with read concern"linearizable"
.$merge
阶段不能与读取关注"linearizable"
一起使用。That is, if you specify也就是说,如果为"linearizable"
read concern fordb.collection.aggregate()
, you cannot include the$merge
stage in the pipeline.db.collection.aggregate()
指定"linearizable"
读取关注,则不能在管道中包含$merge
阶段。
Geospatial Queries地理空间查询-
Using a使用2d
index for queries on spherical data can return incorrect results or an error. For example,2d
indexes don't support spherical queries that wrap around the poles.2d
索引查询球形数据可能会返回不正确的结果或错误。例如,2d
索引不支持环绕极点的球形查询。
Geospatial Coordinates地理空间坐标-
Valid longitude values are between有效的经度值介于-180
and180
, both inclusive.-180
和180
之间(包括-180
和180
)。Valid latitude values are between有效的纬度值介于-90
and90
, both inclusive.-90
和90
之间(包括-90
和90
)。
Area of GeoJSON PolygonsGeoJSON多边形面积-
For对于$geoIntersects
or$geoWithin
, if you specify a single-ringed polygon that has an area greater than a single hemisphere, include the custom MongoDB coordinate reference system in the$geometry
expression.$geoIntersects
或$geoWithin
,如果指定面积大于单个半球的单个环形多边形,请在$geometry
表达式中包含自定义MongoDB坐标参考系。Otherwise,否则,$geoIntersects
or$geoWithin
queries for the complementary geometry.$geoIntersects
或$geoWithin
将查询互补几何体。For all other GeoJSON polygons with areas greater than a hemisphere,对于面积大于半球的所有其他GeoJSON多边形,$geoIntersects
or$geoWithin
queries for the complementary geometry.$geoIntersects
或$geoWithin
查询互补几何体。
Multi-document Transactions多文档事务处理-
For multi-document transactions:对于多文档事务:You can specify read/write (CRUD) operations on existing collections.您可以在现有集合上指定读/写(CRUD)操作。For a list of CRUD operations, see CRUD Operations.有关CRUD操作的列表,请参阅CRUD操作。Starting in MongoDB 4.4, you can create collections and indexes in transactions.从MongoDB 4.4开始,您可以在事务中创建集合和索引。For details, see Create Collections and Indexes In a Transaction有关详细信息,请参阅在事务中创建集合和索引The collections used in a transaction can be in different databases.事务中使用的集合可以在不同的数据库中。NoteYou cannot create new collections in cross-shard write transactions.不能在跨分片写入事务中创建新集合。For example, if you write to an existing collection in one shard and implicitly create a collection in a different shard, MongoDB cannot perform both operations in the same transaction.例如,如果您在一个分片中写入一个现有集合,并在另一个分片中隐式创建一个集合,则MongoDB无法在同一事务中执行这两个操作。You cannot write to capped collections. (Starting in MongoDB 4.2)您不能写入封顶集合。(从MongoDB 4.2开始)You cannot use read concern从封顶集合中读取时,不能使用读取关注"snapshot"
when reading from a capped collection. (Starting in MongoDB 5.0)"snapshot"
。(从MongoDB 5.0开始)You cannot read/write to collections in the无法读取/写入config
,admin
, orlocal
databases.config
、admin
或local
数据库中的集合。You cannot write to无法写入system.*
collections.system.*
集合。You cannot return the supported operation's query plan (i.e.无法返回支持的操作的查询计划(即explain
).explain
)。
For cursors created outside of a transaction, you cannot call对于在事务外部创建的游标,不能在事务内部调用getMore
inside the transaction.getMore
。For cursors created in a transaction, you cannot call对于在事务中创建的游标,不能在事务外调用getMore
outside the transaction.getMore
。
Starting in MongoDB 4.2, you cannot specify从MongoDB 4.2开始,您不能将killCursors
as the first operation in a transaction.killCursors
指定为事务中的第一个操作。
Changed in version 4.44.4版更改.The following operations are not allowed in transactions:事务记录中不允许执行以下操作:Operations that affect the database catalog, such as creating or dropping a collection or an index when using MongoDB 4.2 or lower.影响数据库目录的操作,例如在使用MongoDB 4.2或更低版本时创建或删除集合或索引。Starting in MongoDB 4.4, you can create collections and indexes in transactions unless the transaction is a cross-shard write transaction. For details, see Create Collections and Indexes In a Transaction.从MongoDB 4.4开始,您可以在事务中创建集合和索引,除非事务是跨分片写入事务。有关详细信息,请参阅在事务中创建集合和索引。Creating new collections in cross-shard write transactions.在跨分片写入事务中创建新集合。For example, if you write to an existing collection in one shard and implicitly create a collection in a different shard, MongoDB cannot perform both operations in the same transaction.例如,如果您在一个分片中写入一个现有集合,并在另一个分片中隐式创建一个集合,则MongoDB无法在同一事务中执行这两个操作。Explicit creation of collections, e.g.当使用“local”以外的读取关注级别时,显式创建集合,例如db.createCollection()
method, and indexes, e.g.db.collection.createIndexes()
anddb.collection.createIndex()
methods, when using a read concern level other than"local"
.db.createCollection()
方法,以及索引,例如db.collection.createIndexes()
和db.collection.createIndex()
方法。ThelistCollections
andlistIndexes
commands and their helper methods.listCollections
和listIndexes
命令及其辅助方法。Other non-CRUD and non-informational operations, such as其他非CRUD和非信息性操作,如createUser
,getParameter
,count
, etc. and their helpers.createUser
、getParameter
、count
等及其助手。
Transactions have a lifetime limit as specified by事务具有transactionLifetimeLimitSeconds
.transactionLifetimeLimitSeconds
指定的生存期限制。The default is 60 seconds.默认值为60秒。
Write Command Batch Limit Size写入命令批限制大小-
单个批处理操作允许100,000
writes are allowed in a single batch operation, defined by a single request to the server.100000
次写入,该操作由对服务器的单个请求定义。Changed in version 3.6:3.6版更改:The limit raises from写入次数限制从1,000
to100,000
writes.1000
次提高到100000
次。This limit also applies to legacy此限制也适用于旧式OP_INSERT
messages.OP_INSERT
消息。TheBulk()
operations inmongosh
and comparable methods in the drivers do not have this limit.mongosh
中的Bulk()
操作和驱动程序中的类似方法没有这个限制。
Views视图-
A view definition视图定义pipeline
cannot include the$out
or the$merge
stage.pipeline
不能包含$out
或$merge
阶段。This restriction also applies to embedded pipelines, such as pipelines used in此限制也适用于嵌入式管道,例如$lookup
or$facet
stages.$lookup
或$facet
阶段中使用的管道。Views have the following operation restrictions:视图具有以下操作限制:Views are read-only.视图是只读的。You cannot rename views.不能重命名视图。视图上的find()
operations on views do not support the following Query and Projection Operators operators:find()
操作不支持以下查询运算符和投影运算符:Views视图do not support text search.不支持文本搜索。Views<视图do not support map-reduce operations.不支持map-reduce操作。Views视图do not support geoNear operations (specifically, the不支持geoNear操作(特别是$geoNear
pipeline stage).$geoNear
管道阶段)。
Projection Restrictions投影限制New in version 4.4:4.4版新增:$
-Prefixed Field Path Restriction前缀字段路径限制Starting in MongoDB 4.4, the从MongoDB 4.4开始,find()
andfindAndModify()
projection cannot project a field that starts with$
with the exception of the DBRef fields.find()
和findAndModify()
投影不能投影以$
开头的字段,DBRef字段除外。For example, starting in MongoDB 4.4, the following operation is invalid:例如,在MongoDB 4.4中启动时,以下操作无效:db.inventory.find( {}, { "$instock.warehouse": 0, "$item": 0, "detail.$price": 1 } ) // Invalid starting in 4.4
In earlier version, MongoDB ignores the在早期版本中,MongoDB忽略了前缀为$的字段投影。$
-prefixed field projections.$
Positional Operator Placement Restriction位置运算符安置限制Starting in MongoDB 4.4, the从MongoDB 4.4开始,$
projection operator can only appear at the end of the field path, for example"field.$"
or"fieldA.fieldB.$"
.$
投影运算符只能出现在字段路径的末尾,例如"field.$"
或"fieldA.fieldB.$"
。For example, starting in MongoDB 4.4, the following operation is invalid:例如,在MongoDB 4.4中启动时,以下操作无效:db.inventory.find( { }, { "instock.$.qty": 1 } ) // Invalid starting in 4.4
To resolve, remove the component of the field path that follows the若要解决此问题,请删除$
projection operator.$
投影运算符后面的字段路径的组件。In previous versions, MongoDB ignores the part of the path that follows the在以前的版本中,MongoDB会忽略跟在$
; i.e. the projection is treated as"instock.$"
.$
后面的路径部分;即投影被视为"instock.$"
。Empty Field Name Projection Restriction空字段名称投影限制Starting in MongoDB 4.4,从MongoDB 4.4开始,find()
andfindAndModify()
projection cannot include a projection of an empty field name.find()
和findAndModify()
投影不能包含空字段名的投影。For example, starting in MongoDB 4.4, the following operation is invalid:例如,在MongoDB 4.4中启动时,以下操作无效:db.inventory.find( { }, { "": 0 } ) // Invalid starting in 4.4
In previous versions, MongoDB treats the inclusion/exclusion of the empty field as it would the projection of non-existing fields.在以前的版本中,MongoDB将空字段的包含/排除视为不存在字段的投影。Path Collision: Embedded Documents and Its Fields路径冲突:嵌入文档及其字段Starting in MongoDB 4.4, it is illegal to project an embedded document with any of the embedded document's fields. For example, consider a collection从MongoDB 4.4开始,用嵌入文档的任何字段投影嵌入文档都是非法的。例如,考虑一个包含inventory
with documents that contain asize
field:size
字段的文档的集合inventory
:{ ..., size: { h: 10, w: 15.25, uom: "cm" }, ... }
Starting in MongoDB 4.4, the following operation fails with a从MongoDB 4.4开始,以下操作失败,出现Path collision
error because it attempts to project bothsize
document and thesize.uom
field:Path collision
错误,因为它试图同时投影size
文档和size.uom
字段:db.inventory.find( {}, { size: 1, "size.uom": 1 } ) // Invalid starting in 4.4
In previous versions, lattermost projection between the embedded documents and its fields determines the projection:在以前的版本中,嵌入文档及其字段之间的最新投影决定了投影:If the projection of the embedded document comes after any and all projections of its fields, MongoDB projects the embedded document.如果嵌入文档的投影在其字段的任何和所有投影之后,MongoDB将对嵌入文档进行投影。For example, the projection document例如,投影文档{ "size.uom": 1, size: 1 }
produces the same result as the projection document{ size: 1 }
.{ "size.uom": 1, size: 1 }
产生的结果与投影文档{ size: 1 }
相同。If the projection of the embedded document comes before the projection any of its fields, MongoDB projects the specified field or fields.如果嵌入文档的投影先于其任何字段的投影,MongoDB将投影指定的一个或多个字段。For example, the projection document例如,投影文档{ "size.uom": 1, size: 1, "size.h": 1 }
produces the same result as the projection document{ "size.uom": 1, "size.h": 1 }
.{ "size.uom": 1, size: 1, "size.h": 1 }
产生的结果与投影文档{ "size.uom": 1, "size.h": 1 }
相同。。
Path Collision:路径冲突:数组和嵌入字段的$slice
of an Array and Embedded Fields$slice
Starting in MongoDB 4.4,从MongoDB 4.4开始,find()
andfindAndModify()
projection cannot contain both a$slice
of an array and a field embedded in the array.find()
和findAndModify()
投影不能同时包含数组的$slice
和数组中嵌入的字段。For example, consider a collection例如,考虑一个包含数组字段inventory
that contains an array fieldinstock
:instock
的集合inventory
:{ ..., instock: [ { warehouse: "A", qty: 35 }, { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ], ... }
Starting in MongoDB 4.4, the following operation fails with a从MongoDB 4.4开始,以下操作失败,出现Path collision
error:Path collision
错误:db.inventory.find( {}, { "instock": { $slice: 1 }, "instock.warehouse": 0 } ) // Invalid starting in 4.4
In previous versions, the projection applies both projections and returns the first element (在以前的版本中,投影应用两个投影并返回$slice: 1
) in theinstock
array but suppresses thewarehouse
field in the projected element.instock
数组中的第一个元素($slice:1
),但抑制投影元素中的warehouse
字段。Starting in MongoDB 4.4, to achieve the same result, use the从MongoDB 4.4开始,要获得相同的结果,请使用带有两个独立db.collection.aggregate()
method with two separate$project
stages.$project
阶段的db.collection.aggregate()
方法。$
Positional Operator and$slice
Restriction$
位置运算符和$slice
限制Starting in MongoDB 4.4,从MongoDB 4.4开始,find()
andfindAndModify()
projection cannot include$slice
projection expression as part of a$
projection expression.For example, starting in MongoDB 4.4, the following operation is invalid:find()
和findAndModify()
投影不能包含$slice
投影表达式作为$
投影表达式的一部分。例如,从MongoDB 3.4开始,以下操作无效:db.inventory.find( { "instock.qty": { $gt: 25 } }, { "instock.$": { $slice: 1 } } ) // Invalid starting in 4.4
In previous versions, MongoDB returns the first element (在以前的版本中,MongoDB返回instock.$
) in theinstock
array that matches the query condition; i.e. the positional projection"instock.$"
takes precedence and the$slice:1
is a no-op.instock
数组中与查询条件匹配的第一个元素(instock.$
);即,位置投影"instock.$"
优先,$slice:1
是no-op。The"instock.$": { $slice: 1 }
does not exclude any other document field."instock.$": { $slice: 1 }
不排除任何其他文档字段。
Sessions会话
Sessions and $external Username Limit会话和$external
用户名限制-
To use Client Sessions and Causal Consistency Guarantees with要对$external
authentication users (Kerberos, LDAP, or x.509 users), usernames cannot be greater than 10k bytes.$external
身份验证用户(Kerberos、LDAP或x.509用户)使用客户端会话和因果一致性保证,用户名不能大于10k字节。
Session Idle Timeout会话空闲超时-
Sessions that receive no read or write operations for 30 minutes or that are not refreshed using30分钟内未接收到读取或写入操作的会话,或在此阈值内未使用refreshSessions
within this threshold are marked as expired and can be closed by the MongoDB server at any time.refreshSessions
刷新的会话被标记为过期,MongoDB服务器可以随时关闭这些会话。Closing a session kills any in-progress operations and open cursors associated with the session.关闭会话会杀死任何正在进行的操作和打开的与会话相关的游标。This includes cursors configured with这包括配置为noCursorTimeout()
or amaxTimeMS()
greater than 30 minutes.noCursorTimeout()
或maxTimeMS()
大于30分钟的游标。Consider an application that issues a考虑一个发出db.collection.find()
.db.collection.find()
的应用程序。The server returns a cursor along with a batch of documents defined by the服务器返回一个游标以及cursor.batchSize()
of thefind()
.find()
的cursor.batchSize()
定义的一批文档。The session refreshes each time the application requests a new batch of documents from the server.每当应用程序从服务器请求新的一批文档时,会话都会刷新。However, if the application takes longer than 30 minutes to process the current batch of documents, the session is marked as expired and closed.但是,如果应用程序处理当前一批文档的时间超过30分钟,则会话将标记为过期并关闭。When the application requests the next batch of documents, the server returns an error as the cursor was killed when the session was closed.当应用程序请求下一批文档时,服务器会返回一个错误,因为会话关闭时游标已被终止。For operations that return a cursor, if the cursor may be idle for longer than 30 minutes, issue the operation within an explicit session using对于返回游标的操作,如果游标空闲时间可能超过30分钟,请使用Mongo.startSession()
and periodically refresh the session using therefreshSessions
command.Mongo.startSession()
在显式会话中发出操作,并使用refreshSessions
命令定期刷新会话。For example:例如:var session = db.getMongo().startSession()
var sessionId = session
sessionId //show the sessionId显示会话ID
var cursor = session.getDatabase("examples").getCollection("data").find().noCursorTimeout()
var refreshTimestamp = new Date() //take note of time at operation start注意操作开始时的时间
while (cursor.hasNext()) {
//Check if more than 5 minutes have passed since the last refresh检查自上次刷新以来是否超过5分钟
if ( (new Date()-refreshTimestamp)/1000 > 300 ) {
print("refreshing session")
db.adminCommand({"refreshSessions" : [sessionId]})
refreshTimestamp = new Date()
}
//process cursor normally正常处理游标
}In the example operation, the在示例操作中,db.collection.find()
method is associated with an explicit session.db.collection.find()
方法与一个显式会话相关联。The cursor is configured with游标配置为noCursorTimeout()
to prevent the server from closing the cursor if idle.noCursorTimeout()
,以防止服务器在空闲时关闭游标。Thewhile
loop includes a block that usesrefreshSessions
to refresh the session every 5 minutes.while
循环包括一个块,该块使用refreshSessions
每隔5分钟刷新一次会话。Since the session will never exceed the 30 minute idle timeout, the cursor can remain open indefinitely.由于会话永远不会超过30分钟的空闲超时,因此游标可以无限期地保持打开状态。For MongoDB drivers, defer to the driver documentation for instructions and syntax for creating sessions.对于MongoDB驱动程序,有关创建会话的说明和语法,请参阅驱动程序文档。