MongoDB Limits and Thresholds
On this page
- BSON Documents
- Naming Restrictions
- Namespaces
- Indexes
- Data
- Replica Sets
- Sharded Clusters
- Operations
- Sessions
- Shell
This document provides a collection of hard and soft limitations of the MongoDB system.
BSON Documents
BSON Document SizeThe maximum BSON document size is 16 megabytes.The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth. To store documents larger than the maximum size, MongoDB provides the GridFS API. See
mongofilesand the documentation for your driver for more information about GridFS.
Nested Depth for BSON DocumentsMongoDB supports no more than 100 levels of nesting for BSON documents.
Naming Restrictions
Database Name Case SensitivitySince database names are case insensitive in MongoDB, database names cannot differ only by the case of the characters.
Restrictions on Database Names for WindowsFor MongoDB deployments running on Windows, database names cannot contain any of the following characters:copycopied
/\. "$*<>:|?Also database names cannot contain the null character.Restrictions on Database Names for Unix and Linux SystemsFor MongoDB deployments running on Unix and Linux systems, database names cannot contain any of the following characters:copycopied
/\. "$Also database names cannot contain the null character.Length of Database NamesDatabase names cannot be empty and must have fewer than 64 characters.
Restriction on Collection NamesCollection names should begin with an underscore or a letter character, and cannot:contain the
$.be an empty string (e.g."").contain the null character.begin with thesystem.prefix. (Reserved for internal use.)If your collection name includes special characters, such as the underscore character, or begins with numbers, then to access the collection use thedb.getCollection()method in themongoshell or a similar method for your driver.Namespace Length:For featureCompatibilityVersion set to"4.4"or greater, MongoDB raises the limit on collection/view namespace to 255 bytes. For a collection or a view, the namespace includes the database name, the dot (.) separator, and the collection/view name (e.g.<database>.<collection>),For featureCompatibilityVersion set to"4.2"or earlier, the maximum length of the collection/view namespace remains 120 bytes.
Restrictions on Field NamesField names cannot contain the
nullcharacter.Top-level field names cannot start with the dollar sign ($) character.Otherwise, starting in MongoDB 3.6, the server permits storage of field names that contain dots (i.e..) and dollar signs (i.e.$).IMPORTANTThe MongoDB Query Language cannot always meaningfully express queries over documents whose field names contain these characters (see SERVER-30575).Until support is added in the query language, the use of$and.in field names is not recommended and is not supported by the official MongoDB drivers.MONGODB DOES NOT SUPPORT DUPLICATE FIELD NAMESThe MongoDB Query Language is undefined over documents with duplicate field names. BSON builders may support creating a BSON document with duplicate field names. While the BSON builder may not throw an error, inserting these documents into MongoDB is not supported even if the insert succeeds. 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.
Namespaces
Namespace LengthFor featureCompatibilityVersion set to
"4.4"or greater, MongoDB raises the limit on collection/view namespace to 255 bytes. For a collection or a view, the namespace includes the database name, the dot (.) separator, and the collection/view name (e.g.<database>.<collection>),For featureCompatibilityVersion set to"4.2"or earlier, the maximum length of the collection/view namespace remains 120 bytes.SEE ALSONaming Restrictions
Indexes
Index Key LimitCHANGED IN VERSION 4.2Starting in version 4.2, MongoDB removes the
Index Key Limitfor featureCompatibilityVersion (fCV) set to"4.2"or greater.For MongoDB 2.6 through MongoDB versions with fCV set to"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 theIndex Key Limitapplies:MongoDB will not create an index on a collection if the index entry for an existing document exceeds theindex key limit.Reindexing operations will error if the index entry for an indexed field exceeds theindex key limit. Reindexing operations occur as part of thecompactcommand as well as thedb.collection.reIndex()method.Because these operations drop all the indexes from a collection and then recreate them sequentially, the error from theindex key limitprevents 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 theindex key limit, and instead, will return an error. Previous versions of MongoDB would insert but not index such documents.Updates to the indexed field will error if the updated value causes the index entry to exceed theindex 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.mongorestoreandmongoimportwill not insert documents that contain an indexed field whose corresponding index entry would exceed theindex key limit.In MongoDB 2.6, secondary members of replica sets will continue to replicate documents with an indexed field whose corresponding index entry exceeds theindex key limiton initial sync but will print warnings in the logs.Secondary members also allow index build and rebuild operations on a collection that contains an indexed field whose corresponding index entry exceeds theindex key limitbut 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 theindex key limit.For existing sharded collections, chunk migration will fail if the chunk has a document that contains an indexed field whose index entry exceeds theindex key limit.
Number of Indexes per CollectionA single collection can have no more than 64 indexes.
Index Name LengthCHANGED IN VERSION 4.2Starting in version 4.2, MongoDB removes the
Index Name Length Limitfor MongoDB versions with featureCompatibilityVersion (fCV) set to"4.2"or greater.In previous versions of MongoDB or MongoDB versions with fCV set to"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.By default,<index name>is the concatenation of the field names and index type. You can explicitly specify the<index name>to thecreateIndex()method to ensure that the fully qualified index name does not exceed the limit.Number of Indexed Fields in a Compound IndexThere can be no more than 32 fields in a compound index.
Queries cannot use both text and Geospatial IndexesYou cannot combine the
$textquery, which requires a special text index, with a query operator that requires a different type of special index. For example you cannot combine$textquery with the$nearoperator.Fields with 2dsphere Indexes can only hold GeometriesFields with 2dsphere indexes must hold geometry data in the form of coordinate pairs or GeoJSON data. If you attempt to insert a document with non-geometry data in a
2dsphereindexed field, or build a2dsphereindex on a collection where the indexed field has non-geometry data, the operation will fail.
SEE ALSO
The unique indexes limit in Sharding Operational Restrictions.
NaN values returned from Covered Queries by the WiredTiger Storage Engine are always of type doubleIf the value of a field returned from a query that is covered by an index is
NaN, the type of thatNaNvalue is alwaysdouble.Multikey IndexMultikey indexes cannot cover queries over array field(s).
Geospatial IndexGeospatial indexes cannot cover a query.
Memory Usage in Index BuildscreateIndexessupports building one or more indexes on a collection.createIndexesuses a combination of memory and temporary files on disk to complete index builds. The default limit on memory usage forcreateIndexesis 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 singlecreateIndexescommand. Once the memory limit is reached,createIndexesuses temporary disk files in a subdirectory named_tmpwithin the--dbpathdirectory to complete the build.You can override the memory limit by setting themaxIndexBuildMemoryUsageMegabytesserver parameter. 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.Changed in version 4.2.For feature compatibility version (fcv)"4.2", the index build memory limit applies to all index builds.For feature compatibility version (fcv)"4.0", the index build memory limit only applies to foreground index builds.Index builds may be initiated either by a user command such as Create Index or by an administrative process such as an initial sync. Both are subject to the limit set bymaxIndexBuildMemoryUsageMegabytes.An initial sync operation 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 inmaxIndexBuildMemoryUsageMegabytes.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 TypesThe following index types only support simple binary comparison and do not support collation:text indexes,2d indexes, andgeoHaystack indexes.TIPTo create a
text, a2d, or ageoHaystackindex on a collection that has a non-simple collation, you must explicitly specify{collation: {locale: "simple"} }when creating the index.Hidden IndexesYou cannot hide the
_idindex.You cannot usehint()on a hidden index.Data
Maximum Number of Documents in a Capped CollectionIf you specify a maximum number of documents for a capped collection using the
maxparameter tocreate, the limit must be less than 232 documents. 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 Members of a Replica SetReplica sets can have up to 50 members.
Number of Voting Members of a Replica SetReplica sets can have up to 7 voting members. For replica sets with more than 7 total members, see Non-Voting Members.
Maximum Size of Auto-Created OplogIf you do not explicitly specify an oplog size (i.e. with
oplogSizeMBor--oplogSize) MongoDB will create an oplog that is no larger than 50 gigabytes. [1][1]Starting in MongoDB 4.0, the oplog can grow past its configured size limit to avoid deleting themajority commit point.
Sharded Clusters
Sharded clusters have the restrictions and thresholds described here.
Sharding Operational Restrictions
Operations Unavailable in Sharded Environments$wheredoes not permit references to thedbobject from the$wherefunction. This is uncommon in un-sharded collections.ThegeoSearchcommand is not supported in sharded environments.Covered Queries in Sharded ClustersStarting in MongoDB 3.0, an index cannot cover a query on a sharded collection when run against a
mongosif the index does not contain the shard key, with the following exception for the_idindex: If a query on a sharded collection only specifies a condition on the_idfield and returns only the_idfield, the_idindex can cover the query when run against amongoseven if the_idfield is not the shard key.In previous versions, an index cannot cover a query on a sharded collection when run against amongos.Sharding Existing Collection Data SizeAn 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.Use the following formulas to calculate the theoretical maximum collection size.copycopied
maxSplits = 16777216 (bytes) / <average size of shard key values in bytes> maxCollectionSize (MB) = maxSplits * (chunkSize / 2)NOTEThe maximum BSON document size is 16MB or16777216bytes.All conversions should use base-2 scale, e.g. 1024 kilobytes = 1 megabyte.IfmaxCollectionSizeis less than or nearly equal to the target collection, increase the chunk size to ensure successful initial sharding. 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 Chunk 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 Values512 bytes256 bytes128 bytes64 bytesMaximum Number of Splits32,76865,536131,072262,144Max Collection Size (64 MB Chunk Size)1 TB2 TB4 TB8 TBMax Collection Size (128 MB Chunk Size)2 TB4 TB8 TB16 TBMax Collection Size (256 MB Chunk Size)4 TB8 TB16 TB32 TBSingle Document Modification Operations in Sharded CollectionsAll
update()andremove()operations for a sharded collection that specify thejustOneormulti: falseoption must include the shard key or the_idfield in the query specification.update()andremove()operations specifyingjustOneormulti: falsein a sharded collection which do not contain either the shard key or the_idfield return an error.
Unique Indexes in Sharded CollectionsMongoDB does not support unique indexes across shards, except when the unique index contains the full shard key as a prefix of the index. In these situations MongoDB will enforce uniqueness across the full key, not a single field.SEEUnique Constraints on Arbitrary Fields for an alternate approach.
Maximum Number of Documents Per Chunk to MigrateBy default, MongoDB cannot move a chunk if the number of documents in the chunk is greater than 1.3 times the result of dividing the configured chunk size by the average document size.
db.collection.stats()includes theavgObjSizefield, which represents the average document size in the collection.For chunks that are too large to migrate, starting in MongoDB 4.4:A new balancer settingattemptToBalanceJumboChunksallows the balancer to migrate chunks too large to move as long as the chunks are not labeled jumbo. See Balance Chunks that Exceed Size Limit for details.ThemoveChunkcommand can specify a new option forceJumbo to allow for the migration of chunks that are too large to move. The chunks may or may not be labeled jumbo.
Shard Key Limitations
Shard Key SizeStarting in version 4.4, MongoDB removes the limit on the shard key size.For MongoDB 4.2 and earlier, a shard key cannot exceed 512 bytes.
Shard Key Index TypeA 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 EarlierCHANGED IN VERSION 4.4Starting in MongoDB 4.4, you can refine a collection’s shard key by adding a suffix field or fields to the existing key. See
refineCollectionShardKey.In MongoDB 4.2 and earlier, once you shard a collection, the selection of the shard key is immutable; i.e. you cannot select a different shard key for that collection.If you must change a shard key:Dump all data from MongoDB into an external format.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.Monotonically Increasing Shard Keys Can Limit Insert ThroughputFor clusters with high insert volumes, a shard keys with monotonically increasing and decreasing keys can affect insert throughput. If your shard key is the
_idfield, be aware that the default values of the_idfields are ObjectIds which have generally increasing values.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 OperationsIf MongoDB cannot use an index or indexes to obtain the sort order, MongoDB must perform a blocking sort operation on the data. The name refers to the requirement that the
SORTstage reads all input documents before returning any output documents, blocking the flow of data for that specific query.If MongoDB requires using more than 100 megabytes of system memory for the blocking sort operation, MongoDB returns an error unless the query specifiescursor.allowDiskUse()(New in 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.Changed in version 4.4: For MongoDB 4.2 and prior, blocking sort operations could not exceed 32 megabytes of system memory.For more information on sorts and index use, see Sort and Index Use.
Aggregation Pipeline OperationPipeline stages have a limit of 100 megabytes of RAM. If a stage exceeds this limit, MongoDB will produce an error. To allow for the handling of large datasets, use the
allowDiskUseoption to enable aggregation pipeline stages to write data to temporary files.Changed in version 3.4.The$graphLookupstage must stay within the 100 megabyte memory limit. IfallowDiskUse: trueis specified for theaggregate()operation, the$graphLookupstage ignores the option. If there are other stages in theaggregate()operation,allowDiskUse: trueoption is in effect for these other stages.Starting in MongoDB 4.2, the profiler log messages and diagnostic log messages includes ausedDiskindicator if any aggregation stage wrote data to temporary files due to memory restrictions.SEE ALSO$sort and Memory Restrictions and $group Operator and Memory.Aggregation and Read ConcernStarting in MongoDB 4.2, the
$outstage cannot be used in conjunction with read concern"linearizable". That is, if you specify"linearizable"read concern fordb.collection.aggregate(), you cannot include the$outstage in the pipeline.The$mergestage cannot be used in conjunction with read concern"linearizable". That is, if you specify"linearizable"read concern fordb.collection.aggregate(), you cannot include the$mergestage in the pipeline.2d Geospatial queries cannot use the $or operatorSEE
$orand 2d Index Internals.Geospatial QueriesFor spherical queries, use the
2dsphereindex result.The use of2dindex for spherical queries may lead to incorrect results, such as the use of the2dindex for spherical queries that wrap around the poles.Geospatial CoordinatesValid longitude values are between
-180and180, both inclusive.Valid latitude values are between-90and90, both inclusive.Area of GeoJSON PolygonsFor
$geoIntersectsor$geoWithin, if you specify a single-ringed polygon that has an area greater than a single hemisphere, includethe custom MongoDB coordinate reference system in the $geometryexpression; otherwise,$geoIntersectsor$geoWithinqueries for the complementary geometry. For all other GeoJSON polygons with areas greater than a hemisphere,$geoIntersectsor$geoWithinqueries for the complementary geometry.Multi-document TransactionsFor multi-document transactions:You can specify read/write (CRUD) operations on existing collections. For a list of CRUD operations, see CRUD Operations.When using feature compatibility version (fcv)
"4.4"or greater, you can create collections and indexes in transactions. For details, see Create Collections and Indexes In a TransactionThe 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.You cannot write to capped collections. (Starting in MongoDB 4.2)You cannot read/write to collections in theconfig,admin, orlocaldatabases.You cannot write tosystem.*collections.You cannot return the supported operation’s query plan (i.e.explain).For cursors created outside of a transaction, you cannot callgetMoreinside the transaction.For cursors created in a transaction, you cannot callgetMoreoutside the transaction.Starting in MongoDB 4.2, you cannot specifykillCursorsas the first operation in a transaction.Changed in version 4.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 feature compatibility version (fcv)"4.2"or lower. With fcv"4.4"or greater, 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.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.Explicit creation of collections, e.g.db.createCollection()method, and indexes, e.g.db.collection.createIndexes()anddb.collection.createIndex()methods, when using a read concern level other than"local".ThelistCollectionsandlistIndexescommands and their helper methods.Other non-CRUD and non-informational operations, such ascreateUser,getParameter,count, etc. and their helpers.Transactions have a lifetime limit as specified bytransactionLifetimeLimitSeconds. The default is 60 seconds.Write Command Batch Limit Size100,000writes are allowed in a single batch operation, defined by a single request to the server.Changed in version 3.6: The limit raises from1,000to100,000writes. This limit also applies to legacyOP_INSERTmessages.TheBulk()operations in themongoshell and comparable methods in the drivers do not have this limit.ViewsThe view definition
pipelinecannot include the$outor the$mergestage. If the view definition includes nested pipeline (e.g. the view definition includes$lookupor$facetstage), this restriction applies to the nested pipelines as well.Views have the following operation restrictions:Views are read-only.You cannot rename views.find()operations on views do not support the following projection operators:$$elemMatch$slice$metaViews do not support text search.Views do not support map-reduce operations.Views do not support geoNear operations (i.e.$geoNearpipeline stage).Projection RestrictionsNew in version 4.4:
$-Prefixed Field Path RestrictionStarting in MongoDB 4.4, thefindandfindAndModifyprojection cannot project a field that starts with$with the exception of the DBRef fields.For example, starting in MongoDB 4.4, the following operation is invalid:db.inventory.find( {}, { "$instock.warehouse": 0, "$item": 0, "detail.$price": 1 } ) // Invalid starting in 4.4MongoDB already has arestrictionwhere top-level field names cannot start with the dollar sign ($).In earlier version, MongoDB ignores the$-prefixed field projections.$Positional Operator Placement RestrictionStarting in MongoDB 4.4, the$projection operator can only appear at the end of the field path; e.g."field.$"or"fieldA.fieldB.$".For example, starting in MongoDB 4.4, the following operation is invalid:db.inventory.find( { }, { "instock.$.qty": 1 } ) // Invalid starting in 4.4To 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$; i.e. the projection is treated as"instock.$".Empty Field Name Projection RestrictionStarting in MongoDB 4.4,findandfindAndModifyprojection cannot include a projection of an empty field name.For example, starting in MongoDB 4.4, the following operation is invalid:db.inventory.find( { }, { "": 0 } ) // Invalid starting in 4.4In previous versions, MongoDB treats the inclusion/exclusion of the empty field as it would the projection of non-existing fields.Path Collision: Embedded Documents and Its FieldsStarting in MongoDB 4.4, it is illegal to project an embedded document with any of the embedded document’s fields.For example, consider a collectioninventorywith documents that contain asizefield:{ ..., size: { h: 10, w: 15.25, uom: "cm" }, ... }Starting in MongoDB 4.4, the following operation fails with aPath collisionerror because it attempts to project bothsizedocument and thesize.uomfield:db.inventory.find( {}, { size: 1, "size.uom": 1 } ) // Invalid starting in 4.4In 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. For example, the projection document{ "size.uom": 1, size: 1 }produces the same result as the projection document{ size: 1 }.If the projection of the embedded document comes before the projection any of its fields, MongoDB projects the specified field or fields. 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 }.Path Collision:$sliceof an Array and Embedded FieldsStarting in MongoDB 4.4,findandfindAndModifyprojection cannot contain both a$sliceof an array and a field embedded in the array.For example, consider a collectioninventorythat contains an array fieldinstock:{ ..., instock: [ { warehouse: "A", qty: 35 }, { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ], ... }Starting in MongoDB 4.4, the following operation fails with aPath collisionerror:db.inventory.find( {}, { "instock": { $slice: 1 }, "instock.warehouse": 0 } ) // Invalid starting in 4.4In previous versions, the projection applies both projections and returns the first element ($slice: 1) in theinstockarray but suppresses thewarehousefield in the projected element. Starting in MongoDB 4.4, to achieve the same result, use thedb.collection.aggregate()method with two separate$projectstages.$Positional Operator and$sliceRestrictionStarting in MongoDB 4.4,findandfindAndModifyprojection cannot include$sliceprojection expression as part of a$projection expression.For example, starting in MongoDB 4.4, the following operation is invalid:db.inventory.find( { "instock.qty": { $gt: 25 } }, { "instock.$": { $slice: 1 } } ) // Invalid starting in 4.4MongoDB already has arestrictionwhere top-level field names cannot start with the dollar sign ($).In previous versions, MongoDB returns the first element (instock.$) in theinstockarray that matches the query condition; i.e. the positional projection"instock.$"takes precedence and the$slice:1is a no-op. The"instock.$": { $slice: 1 }does not exclude any other document field.Sessions
Sessions and $external Username LimitChanged in version 3.6.3: To use sessions with
$externalauthentication users (i.e. Kerberos, LDAP, x.509 users), the usernames cannot be greater than 10k bytes.Session Idle TimeoutSessions that receive no read or write operations for 30 minutes or that are not refreshed using
refreshSessionswithin this threshold are marked as expired and can be closed by the MongoDB server at any time. Closing a session kills any in-progress operations and open cursors associated with the session. This includes cursors configured withnoCursorTimeoutor amaxTimeMSgreater than 30 minutes.Consider an application that issues adb.collection.find(). The server returns a cursor along with a batch of documents defined by thecursor.batchSize()of thefind(). 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. 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 usingSession.startSession()and periodically refresh the session using therefreshSessionscommand. For example:copycopiedvar session = db.getMongo().startSession() var sessionId = session.getSessionId().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 if ( (new Date()-refreshTimestamp)/1000 > 300 ) { print("refreshing session") db.adminCommand({"refreshSessions" : [sessionId]}) refreshTimestamp = new Date() } // process cursor normally }In the example operation, thedb.collection.find()method is associated with an explicit session. The cursor is configured withnoCursorTimeout()to prevent the server from closing the cursor if idle. Thewhileloop includes a block that usesrefreshSessionsto refresh the session every 5 minutes. Since the session will never exceed the 30 minute idle timeout, the cursor can remain open indefinitely.For MongoDB drivers, defer to the driver documentation for instructions and syntax for creating sessions.Shell
The mongo shell prompt has a limit of 4095 codepoints for each line. If you enter a line with more than 4095 codepoints, the shell will truncate it.