MongoDB counts, distinct, cursors and read-path tuning
Parent: Global AI Hub Research Corpus · Published reference · snapshot 2026-10-19
↓ Facts as markdownall context files
Everything the scanned sources say about MongoDB counts, distinct, cursors and read-path tuning: 948 source-anchored units across 5 sources, grouped by facet.
These notes link each claim to its source. Some citations identify archived research reports that are no longer hosted on this site. A published reference means the content is available; it does not certify independent review or accuracy.Read the editorial policy and follow the sources before relying on a claim.
Definitions
- If the result of the query is not sorted, the mongos instance opens a result cursor that "round robins" results from all cursors on the shards. [source]
- $sample is the first stage of the pipeline. [source]
- Only present if the cursor is not idle. [source]
- `myCount` is the output field that stores the count. You can specify another name for the output field. [source]
- If the value of the specified `field` is an array, [`db.collection.distinct()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#mongodb-method-db.collection.distinct) considers each element of the array as a separate value. [source]
- If the returned cursor is not assigned to a variable using the `let` keyword, then the cursor is automatically iterated up to the batch size, printing the first batch of results. [source]
- A `batchSize` of `0` means that the cursor is established, but no documents are returned in the first batch. [source]
- The MongoDB MCP Server is a tool that allows you to interact with your MongoDB clusters in natural language by integrating with AI clients like Claude, Cursor, and GitHub Copilot. [source]
Structure and components
- | Field | Description | Applicable Stages | | --- | --- | --- | | `docsExamined` | Specifies the number of documents scanned during the query execution stage. | `COLLSCAN`, `FETCH` | | `keysExamined` | For query execution stages that scan an index `keysExamined` is the total number of in-bounds and out-of-bounds keys that are examined in the process of the index scan. If the index scan consists of a single contiguous range of keys, only in-bounds keys need to be examined. If the index bounds consists of several key ranges, the index scan execution process may examine out-of-bounds keys in orde [source]
- If, however, the query can use an index but the query predicates do not access a single contiguous range of index keys or the query also contains conditions on fields outside the index, then in addition to using the index, MongoDB must also read the documents to return the count. [source]
- The pseudo-random cursor doesn't guarantee a uniform random sample. It selects documents by descending the collection's internal B-tree structure at random, so the results can skew toward some parts of the collection. Skew is more likely when: [source]
- | Option | Description | | --- | --- | | [allUsers](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#std-label-currentOp-stage-allUsers) | Boolean. If set to `false`, `$currentOp` only reports on operations/idle connections/idle cursors/idle sessions belonging to the user who ran the command.; If set to `true`, `$currentOp` reports operations belonging to all users. For standalone and replica sets that enforce access control, `inprog` privilege is required if `allUsers: true`. For sharded clusters that enforce access control, the `inprog` privilege is required to [source]
- A document that contains metrics for cursors used by [`mongos`.](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) [source]
- The total number of [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) operations since the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instance last started. This counter can be high even if the query count is low. Secondary nodes send [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) operations as part of the replication process. [source]
- The total number queries that performed a collection scan. The total consists of queries that did and did not use a [tailable cursor.](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) [source]
- | Database Tool Name | Description | | --- | --- | | `list-databases` | Displays all databases available in your MongoDB deployment with their storage sizes. | | `list-collections` | Shows all collections within a specific database. | | `find` | Retrieves actual documents from a collection that match specific search criteria. | | `count` | Quickly returns the total number of documents in a collection without retrieving the documents themselves. | | `aggregate` | Performs complex data processing operations like grouping, filtering, transforming, and calculating statstics across documents. | | ` [source]
- - If `hasSort` is set to `true`, this indicates that the query contains a [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method. Unindexed [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) methods can be very resource intensive. Check your search index configuration and confirm whether it supports the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method. [source]
- If you count the number of documents in the `movies` collection and include a hint that specifies that sparse index, the operation returns only the documents that contain the `rated` field. [source]
- | Document | Description | | --- | --- | | `key` | The unique combination of attributes that define an entry in the query stats output. The `key` contains attributes such as: [Query shape](https://www.mongodb.com/docs/manual/core/query-shapes.md#std-label-query-shapes); Client information; Read concern; [Collection type](https://www.mongodb.com/docs/manual/reference/operator/aggregation/querystats.md#std-label-queryStats-collectionType) Each unique combination of attributes creates a separate entry in the `$queryStats` virtual collection. | | `asOf` | The UTC time when `$queryStats` read this [source]
- This example counts the number of documents in the `movies` collection where the `directors` field contains `"David Lynch"`: [source]
- The following example output contains the command object for a [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) operation generated by a command with cursor ID `19234103609` on a collection named `items` in a database named `test`: [source]
- A document that contains the cursor information for `idleCursor` and `getmore` operations; i.e. where [`type`](https://www.mongodb.com/docs/manual/reference/command/currentop.md#mongodb-data-currentOp.type) is `idleCursor` or [`op`](https://www.mongodb.com/docs/manual/reference/command/currentop.md#mongodb-data-currentOp.op) is `getmore`. [source]
- The `originatingCommand` field contains the full command object (e.g. `find` or `aggregate`) which originally created the cursor. [source]
- Passes a document to the next stage that contains a count of the number of documents input to the stage. [source]
- `<string>` is the name of the output field which has the count as its value. `<string>` must be a non-empty string, must not start with `$` and must not contain the `.` character. [source]
- For "getmore" operations which retrieve the next batch of results from a cursor, the originatingCommand field contains the full command object (e.g. find or aggregate) which originally created that cursor. [source]
- The command returns a document that contains the cursor information and the next batch. [source]
- | Field | Description | | --- | --- | | `cursor` | Contains the cursor information, including the cursor ID and the `nextBatch` of documents. If [`find`](https://www.mongodb.com/docs/manual/reference/command/find.md#mongodb-dbcommand-dbcmd.find) (or subsequent [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) commands) returns partial results because the queried shard(s) aren't available, the [find output](https://www.mongodb.com/docs/manual/reference/command/find.md#std-label-cmd-find-output) includes a `partialResultsReturned` indic [source]
- | Field | Description | | --- | --- | | `samplingRate` | The sampling rate used to mirror a subset of [operations that support mirroring](https://www.mongodb.com/docs/manual/replication.md#std-label-mirrored-reads-supported-operations) to a subset of electable (specifically, [`priority greater than 0`](https://www.mongodb.com/docs/manual/reference/replica-configuration.md#mongodb-rsconf-rsconf.members-n-.priority)) secondaries. That is, the primary mirrors reads to each electable secondary at the specified sampling rate. Valid values are: `0.0`Turns off mirroring.`1.0`The primary mirrors all [source]
- A modified cursor object that contains the document fields and the appended `$recordId` field. [source]
- [`metrics.repl.network.getmores`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.repl.network.getmores) reports on the `getmore` operations, which are requests for additional results from the oplog [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) as part of the oplog replication process. [source]
- A document that contains data regarding cursor state and use. [source]
- A document that contains data regarding open cursors. [source]
- You can retrieve details about the queries that were run in the past 7 days using `$queryHistory` (aggregation). `$queryHistory` returns documents, one per query, that contain information about the [aggregate](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#std-label-aggregate-database-command), [find](https://www.mongodb.com/docs/manual/reference/command/find.md#std-label-find-database-command), and [count](https://www.mongodb.com/docs/manual/reference/command/count.md#std-label-count-database-command) queries that were run in the past 7 days. You can filter on the fields r [source]
- Each output document contains two fields: an `_id` field containing the distinct grouping value, and a `count` field containing the number of documents belonging to that grouping or category. [source]
- | Field | Description | | --- | --- | | `_id` | Inclusive lower bound of the bucket. | | `count` | Count of documents in the bucket. | | `artists` | Array of documents containing information on each artist in the bucket. Each document contains the artist's `name`, which is a concatenation (i.e. [`$concat`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/concat.md#mongodb-expression-exp.-concat)) of the artist's `first_name` and `last_name`.; `year_born` | [source]
- While automatic encryption does not encrypt the getMore command, the response to the command may contain encrypted field values. [source]
- Execution metrics such as totalExecMicros contain information for the most recent operation (cursor creation, getMore, or cursor close). [source]
- Object that contains two fields: true and false. Each field counts the number of matching queries where the value of hasSortStage is true or false, respectively. [source]
- Object that contains two fields: true and false. Each field counts the number of matching queries where the value of usedDisk is true or false, respectively. [source]
- Object that contains two fields: true and false. Each field counts the number of matching queries where the value of fromMultiPlanner is true or false, respectively. [source]
- Object that contains two fields: true and false. Each field counts the number of matching queries where the value of fromPlanCache is true or false, respectively. [source]
- Contains counts for each cardinality estimation method used during cost-based ranking. Each field represents the number of times a particular estimation method was used. [source]
- MongoDB omits counters with a count of zero and omits subdocuments that contain no counters. If none of the recorded queries produced plan shape counters, MongoDB omits the planShapeCounters document entirely. For example, a query that matches a single document by _id uses a fast path that doesn't match any tracked plan shape, so its query stats entry contains no planShapeCounters document. [source]
- - A `count` field that contains the number of documents in the bucket. The `count` field is included by default when the `output` document is not specified. [source]
- | Field | Type | Description | | --- | --- | --- | | `groupBy` | expression | An [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) to group documents by. To specify a [field path](https://www.mongodb.com/docs/manual/core/aggregation-pipeline.md#std-label-agg-quick-ref-field-paths), prefix the field name with a dollar sign `$` and enclose it in quotes. | | `buckets` | integer | A positive 32-bit integer that specifies the number of buckets into which input documents are grouped. | | `output` | document | Optional. A document that sp [source]
- You can apply `$unwind` multiple times in a single pipeline to expand documents that contain several array fields. The following operation unwinds the `genres` array and then the `cast` array to produce a flat document for every genre-actor combination, then groups by genre to count the total cast appearances in each genre: [source]
- Messages related to database commands, such as count. To specify the log level for COMMAND components, use the systemLog.component.command.verbosity setting. [source]
- This section contains examples that use a cursor to read documents from a collection with temperature readings from a weather sensor. You'll see examples of `isExhausted()`. [source]
How it works
- If you include a [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) that specifies a [sparse index](https://www.mongodb.com/docs/manual/core/index-sparse.md#std-label-index-type-sparse) when you perform a [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) of all documents in a collection (i.e. with an empty query predicate), the sparse index is used even if the sparse index results in an incorrect count. [source]
- When you call [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) on a [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) operation which does not specify a query predicate, the [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) method can return inaccurate document counts. These [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) methods return results [source]
- On a sharded cluster, [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) without a query predicate in the `find` can result in an *inaccurate* count if [orphaned documents](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-orphaned-document) exist or if a [chunk migration](https://www.mongodb.com/docs/manual/core/sharding-balancer-administration.md#std-label-sharding-balancing) is in progress. [source]
- - When an [index filter](https://www.mongodb.com/docs/manual/core/query-plans.md#std-label-index-filters) exists for the query shape, MongoDB ignores the [`hint()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) [source]
- The [query optimizer](https://www.mongodb.com/docs/manual/core/query-plans.md#std-label-read-operations-query-optimization) typically selects the optimal index for a specific operation. However, you can force MongoDB to use a specific index using the [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) method. Use [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) to support performance testing or when you are querying a field that appears in several indexes to ensure that MongoDB uses [source]
- Every read preference mode except primary may return stale data because secondaries replicate asynchronously. maxStalenessSeconds lets the client skip secondaries whose estimated lag is too high. The modes secondary and secondaryPreferred compare lag with the primary; primaryPreferred and nearest compare with the freshest secondary when there is no primary. [source]
- [`itcount()`](https://www.mongodb.com/docs/manual/reference/method/cursor.itcount.md#mongodb-method-cursor.itcount) is similar to [`cursor.count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count), but actually executes the query on an existing iterator, exhausting its contents in the process. [source]
- [`min()`](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) exists primarily to support the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) process. [source]
- This point-in-time value is distinct from [`metrics.changeStreams.cursor.totalOpened`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.changeStreams.cursor.totalOpened), which is a cumulative count. Use this value to assess how heavily change streams use this process. [source]
- [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) exists primarily to support the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) (sharding) process. [source]
- The [MongoCollection.find()](https://mongodb.github.io/mongo-java-driver/5.11/apidocs/driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-mongo-collection/find.html) method returns an instance of the [FindFlow](https://mongodb.github.io/mongo-java-driver/5.11/apidocs/driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-find-flow/index.html) class. [source]
- When specifying [`linearizable read concern`](https://www.mongodb.com/docs/manual/reference/read-concern-linearizable.md#mongodb-readconcern-readconcern.-linearizable-), always use [`maxTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxtimems.md#mongodb-method-cursor.maxTimeMS) in case a majority of data bearing members are unavailable. [source]
- For sharded clusters, mongos applies the read preference when reading from the shards. The member selected is governed by both the read preference and replication.localPingThresholdMs settings, and is re-evaluated for each operation. [source]
- Views are the result of aggregation pipelines. When you use $sample on a view, MongoDB appends the stage to the end of the view's aggregation pipeline syntax. Therefore, the $sample stage on a view is never the first stage and always results in a collection scan. [source]
- Because index filters override the expected behavior of the planner as well as the [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) method, use index filters sparingly. [source]
- When executing [`$or`](https://www.mongodb.com/docs/manual/reference/operator/query/or.md#mongodb-query-op.-or) queries with a [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort), MongoDB can use indexes that support the [`$or`](https://www.mongodb.com/docs/manual/reference/operator/query/or.md#mongodb-query-op.-or) clauses. [source]
- - Use an index to satisfy the sort so that MongoDB doesn't sort documents in memory. To learn more, see [Sort and Index Use.](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-index-use) [source]
- Setting [`cursorTimeoutMillis`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.cursorTimeoutMillis) to less than or equal to `0` results in all cursors being immediately eligible for timeout. Generally, the timeout value should be greater than the average amount of time for a query to return results. Use tools like the [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) cursor modifier to analyze the average query time and select an appropriate timeout period. [source]
- When possible, [`db.collection.distinct()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#mongodb-method-db.collection.distinct) operations can use indexes. [source]
- Specifies the *inclusive* lower bound for a specific index in order to constrain the results of [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find). [`min()`](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) provides a way to specify lower bounds on compound key indexes. [source]
- Because [`min()`](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) requires an index on a field, and forces the query to use this index, you may prefer the [`$gte`](https://www.mongodb.com/docs/manual/reference/operator/query/gte.md#mongodb-query-op.-gte) operator for the query if possible. Consider the following example: [source]
- The [change streams](https://www.mongodb.com/docs/manual/changeStreams/) cursors that the MongoDB Search process (`mongot`) uses to keep MongoDB Search indexes updated can contribute to the query targeting ratio and trigger [query targeting alerts](https://www.mongodb.com/docs/atlas/reference/alert-conditions.md#std-label-query-targeting-alerts) if the ratio is high. [source]
- Specifies the *exclusive* upper bound for a specific index in order to constrain the results of [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find). [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) provides a way to specify an upper bound on compound key indexes. [source]
- Because [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) requires an index on a field, and forces the query to use this index, you may prefer the [`$lt`](https://www.mongodb.com/docs/manual/reference/operator/query/lt.md#mongodb-query-op.-lt) operator for the query if possible. Consider the following example: [source]
- | Counter | Description | | --- | --- | | `collscan``clusteredCollscan` | Collection scans, counted separately based on whether the scan uses the [clustered index.](https://www.mongodb.com/docs/manual/core/clustered-collections.md#std-label-clustered-collections) | | `coveredIxscan` | Index scans that don't fetch documents. | | `ixscanFetch` | Index scans that fetch documents. | | `countScan` | Scans that count index keys without returning documents. | | `distinctScan``distinctScanFetch` | Scans that skip duplicate index keys, counted separately based on whether the scan fetches documents. | | [source]
- The time reported by `explain.executionStats.executionTimeMillis` is not necessarily representative of actual query time. During steady state operations (when the query plan is cached), or when using [`cursor.hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) with `cursor.explain()`, MongoDB bypasses the plan selection process, resulting in a faster actual time, leading to a lower `explain.executionStats.executionTimeMillis` value. [source]
- The number of times that we had to seek the index cursor to a new position in order to complete the index scan. [source]
- A filtered count is covered when an index holds all filter fields; verify with explain('executionStats') showing a COUNT_SCAN stage and totalDocsExamined: 0. [source]
- When you call [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) without a query predicate, you may receive inaccurate document counts. Without a query predicate, [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) commands return results based on the collection's metadata, which may result in an approximate count. In particular, [source]
- - If you use the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method in your query, MongoDB performs a second sort operation, re-ordering the matching documents. When querying large collections, this can negatively affect query performance. [source]
- Without a query predicate, `count()` returns results based on the collection's metadata, which may result in an incorrect count. In particular, [source]
- `$clusterTime` is the timestamp from the [oplog](https://www.mongodb.com/docs/manual/core/replica-set-oplog.md#std-label-replica-set-oplog) entry when the `cakeSales` collection is modified. See [Command Response.](https://www.mongodb.com/docs/manual/reference/method/db.runcommand.md#std-label-command-response) [source]
- | Name | Description | | --- | --- | | [`$accumulator`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#mongodb-group-grp.-accumulator) | Returns the result of a user-defined accumulator function. | | [`$addToSet`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/addtoset.md#mongodb-group-grp.-addToSet) | Returns an array of *unique* expression values for each group. Order of the array elements is undefined. | | [`$avg`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/avg.md#mongodb-group-grp.-avg) | Returns an average of n [source]
- For example, `$group` operations of the following form can result in a `DISTINCT_SCAN`: [source]
- When you use `countDocuments()` in a transaction, the resulting count will not filter out any uncommitted [multi-document transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions) [source]
- The date and time when the cursor was created. [source]
- The date and time when the cursor was last used. [source]
- The flag that indicates that the cursor doesn't timeout when idle; i.e. if the cursor has the `noTimeout` option set. [source]
- - If true, the cursor does not time out when idle. [source]
- - If false, the cursor times out when idle. [source]
- The flag that indicates if the cursor is a [tailable cursor](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) for a capped collection. Tailable cursors remain open after the client exhausts the results in the initial cursor. [source]
- The total number of documents in the collection is also available as `storageStats.count` when `storageStats: {}` is specified. For more information, see [storageStats Document.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#std-label-storage-stats-document) [source]
- - Set the value substantially higher than the change stream's `maxTimeMS` or `maxAwaitTimeMS` value, but lower than the network timeout value. A value that is too low causes oplog scans to bail out too frequently, which limits the progress that each command makes and can cause the change stream to fall behind the write workload. [source]
- Controls how the server responds when an unauthenticated client sends a streaming [`hello`](https://www.mongodb.com/docs/manual/reference/command/hello.md#mongodb-dbcommand-dbcmd.hello) command with a `maxAwaitTimeMS` value below the [`minWaitForStreamingHelloMillis`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.minWaitForStreamingHelloMillis) floor: [source]
- When you use countDocuments() in a transaction, the resulting count will not filter out any uncommitted multi-document transactions. [source]
- Configures the cursor to display results in a format that is easy to read. [source]
- In [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh), the cursor does not automatically iterate when you assign it to a variable using the `let` keyword. [source]
- The following example selects documents to process using the [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) pipeline operator and then pipes the results to the [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) pipeline operator to compute a count of the documents: [source]
- Counts how many write‑mode lock requests wait because another operation holds the lock. [source]
- For [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) commands, the histogram is only incremented when a `batchSize` value is set on the command. For [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) commands that don't set a `batchSize` value, the server applies a backfill value and increments the corresponding bucket. [source]
- A document that reports throughput and cursor statistics for the change stream cursors that this process maintains. [source]
- A document that reports the lifespans of the change stream cursors that have closed in this process. A cursor lifespan is the duration between the time the cursor opens and the time the cursor closes. [source]
- The values update when a cursor closes and don't account for cursors that are still open. [source]
- The exponential moving average lifespan, in microseconds, of the change stream cursors that have closed in this process. Recent cursors contribute more to this value than earlier cursors. [source]
- The total number of change stream cursors that have closed in this process. [source]
- A document that reports the number of change stream cursors currently open in this process. [source]
- This value is always less than or equal to [`metrics.changeStreams.cursor.open.total`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.changeStreams.cursor.open.total), because open cursors can be idle. Compare the two values to see how change stream activity divides between active and idle cursors. [source]
- The number of change stream cursors currently open in this process, including both idle and pinned cursors. [source]
- The cumulative number of change stream cursors opened in this process, including cursors that have since closed. The value increases when a cursor opens, including when a change stream resumes, and doesn't decrease when a cursor closes. [source]
- The number of times a change stream cursor failed to resume because the requested resume point is no longer available in the oplog. [source]
- The total number of cursors that have returned more than one batch since the server process started. Additional batches are retrieved using the [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) command. [source]
- A document that reports the number of cursors that have lifespans within specified time periods. The cursor lifespan is the time period from when the cursor is created to when the cursor is killed using the [`killCursors`](https://www.mongodb.com/docs/manual/reference/command/killcursors.md#mongodb-dbcommand-dbcmd.killCursors) command or the cursor has no remaining objects in the [batch.](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursor-batches) [source]
- The number of cursors that MongoDB is maintaining for clients. Because MongoDB exhausts unused cursors, typically this value small or zero. However, if there is a queue, or stale tailable cursors, or a large number of operations this value may increase. [source]
- When you use db.collection.estimatedDocumentCount() in a transaction, the resulting count will not filter out any uncommitted multi-document transactions. [source]
- A [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) to the documents that match the `query` criteria. When `find()` "returns documents," the method is actually returning a cursor to the documents. [source]
- Because $queryStats reports only the operations that MongoDB samples, its output represents a subset of the operations run against your deployment. Counts and execution times reflect only the sampled operations. [source]
- firstResponseExecMicros and totalExecMicros are always the same because stats are collected and updated for each getMore operation. [source]
- When the cursor closes, lastExecutionMicros is 0. [source]
- hasSortStage is true when MongoDB must sort the documents after it receives the documents from a cursor. [source]
- The command returns a document with cursor information, including the [cursor ID](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursor-id) and the first batch of documents. The following example shows the output when run against a sharded collection: [source]
- Starting in MongoDB 7.3, when you use a find command on a view with the `singleBatch: true` and `batchSize: 1` options, a cursor is no longer returned. In previous versions of MongoDB these find queries would return a cursor even when you set the [single batch](https://www.mongodb.com/docs/manual/reference/command/find.md#std-label-find-single-batch) option to `true`. [source]
- - `firstResponseExecMicros` and `totalExecMicros` are always the same because stats are collected and updated for each `getMore` operation. [source]
- - When using the [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#mongodb-pipeline-pipe.-collStats) stage, only the `count` field is available. All other [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#mongodb-pipeline-pipe.-collStats) fields are not available in Stable API V1. [source]
- Marks the cursor as [tailable](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) keeping it open even when the client exhausts all results. [source]
- If `awaitData` is `true`, when the cursor reaches the end of the capped collection, [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-program-mongod) blocks the query thread for the timeout interval and waits for new data to arrive. When new data is inserted into the capped collection, `mongod` signals the blocked thread to wake and return the next batch to the client. [source]
- The MongoDB instance returns response in batches. To retrieve all the documents from a cursor may require multiple batch responses from the MongoDB instance. When there are no more documents remaining in the current batch, the cursor will retrieve another batch to get more documents until the cursor exhausts. [source]
- - Because the 31st is a Sunday and it is between `startDate` and `endDate`, one `week` is added to the count. [source]
- - The `week` count is incremented even when a calendar week finishes after `endDate` or in the next calendar period. [source]
- The Query Profiler samples operations by using a bucketing algorithm that adjusts the sample size based on the width of the selected time range. Because of differences in bucket size, a wider time range might display fewer sampled operations than a narrower time range. For exact, unsampled operation counts, download your `mongod` logs. To learn more, see [View and Download MongoDB Logs.](https://www.mongodb.com/docs/atlas/mongodb-logs.md#std-label-mongodb-logs) [source]
- - If the deployment is a sharded cluster, a shard removal may cause an open change stream cursor to close. The closed change stream cursor may not be fully resumable. [source]
- The [Mongo::Collection#find()](https://www.mongodb.com/docs/ruby-driver/current/api/Mongo/Collection.html#find-instance_method) method returns a [CollectionView](https://www.mongodb.com/docs/ruby-driver/current/api/Mongo/Collection/View.html), which is an `Enumerable`. A [Cursor](https://www.mongodb.com/docs/ruby-driver/current/api/Mongo/Cursor.html) is created when the `View` is enumerated; for example, by calling `#to_a()` or `#each()`. You can also get an `Enumerator` by calling `#to_enum()` on the `View`. See the Ruby driver API documentation for [iterating over a cursor.](https://www.mong [source]
- When you run a find operation with a MongoDB driver or `mongosh`, MongoDB returns a [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) that manages query results. Query results are not returned as an array of documents. [source]
- You can use `isExhausted()` with a [tailable cursor](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page). A tailable cursor stays open even if no documents remain in the current batch. Other cursors are automatically closed when no documents remain. [source]
- The following example adds the `DBQuery.Option.tailable` flag and the `DBQuery.Option.awaitData` flag to ensure that the query returns a [tailable cursor](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page). The sequence creates a cursor. After returning the full result set, it waits for the default interval of 1000 milliseconds so that it can capture and return additional data added during the query: [source]
How-to and procedures
- To obtain the correct count of the number of documents in the `movies` collection, do not [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) with a [sparse index](https://www.mongodb.com/docs/manual/core/index-sparse.md#std-label-index-type-sparse) when performing a count of all documents in a collection. [source]
- To see whether MongoDB will apply an index filter for a plan cache query shape, check the [`indexFilterSet`](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.queryPlanner.indexFilterSet) field of either the [`db.collection.explain()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) or the [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) method. [source]
- To target secondaries with specific tags, include both the [mode](https://www.mongodb.com/docs/manual/reference/method/cursor.readpref.md#std-label-cursor-readpref-mode) and the [tagSet](https://www.mongodb.com/docs/manual/reference/method/cursor.readpref.md#std-label-cursor-readpref-tagset) array: [source]
- Use read isolation to improve consistency. To learn more, see [Read Concern `"snapshot"`.](https://www.mongodb.com/docs/manual/reference/read-concern-snapshot.md#std-label-read-concern-snapshot) [source]
- To override the default read concern level, use the `readConcern` option. The [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) command uses the `readConcern` level specified in the originating [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) command. [source]
- To see whether your operation results in a `DISTINCT_SCAN`, check your operation's [explain results.](https://www.mongodb.com/docs/manual/reference/explain-results.md#std-label-explain-results) [source]
- To view the query plan information for a given query, you can use [`db.collection.explain()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) or the [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) . [source]
- Use the [`db.collection.explain()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) or the [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) method in [executionStats](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#std-label-explain-method-executionStats) mode to return statistics about the query process, including the index used, the number of documents scanned, and the time the query takes to process in milliseconds. [source]
- Run [`db.collection.explain()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) or the [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) method in [allPlansExecution](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#std-label-explain-method-allPlansExecution) mode to view partial execution statistics collected during plan selection. [source]
- To view the execution statistics for a specific index, append to the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) the [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) method followed by [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain), e.g.: [source]
- Use `$natural` in conjunction with `cursor.hint()` to perform a collection scan to return documents in [natural order.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-natural-order) [source]
- To force MongoDB to use a particular index, use cursor.hint() (mongosh method) when testing indexes. [source]
- To use an index with the [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) method, you must use the [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) method to specify the index you want to use, except when the [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) query is an equality condition on the `_id` field. [source]
- To confirm whether a query used an index, run the query with the [`explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) option. [source]
- To view the query plan selected, chain the [`cursor.explain("executionStats")`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) cursor method to the end of the **find** command: [source]
- To view the query plan statistics, use the [`explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) method: [source]
- To manually compare the performance of a query using more than one index, you can use the [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) method in conjunction with the [`explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) method. [source]
- To determine whether a pipeline uses indexes, review the query plan and look for `IXSCAN` or `DISTINCT_SCAN` plans. [source]
- To use the sparse index, explicitly specify the index with [`hint()`:](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) [source]
- To count the number of documents in the `movies` collection, use the following operation: [source]
- To use the MongoDB .NET/C# driver to add a $sample stage to an aggregation pipeline, call the UnionWith() method on a PipelineDefinition object. [source]
- To use the MongoDB Node.js driver to add a $sample stage to an aggregation pipeline, use the $sample operator in a pipeline object. [source]
- To achieve a *consistent sort*, add a field which contains exclusively unique values to the sort. The following command uses the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method to sort on both the `borough` field and the `_id` field: [source]
- To select multiple values for a field, click and drag the cursor over a selection of values, or press shift+click on the desired values. [source]
- Use with commands that return a cursor, such as [`find`](https://www.mongodb.com/docs/manual/reference/command/find.md#mongodb-dbcommand-dbcmd.find) and [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate), to return the next document batches from a cursor. [source]
- Create a [change stream cursor](https://www.mongodb.com/docs/manual/changestreams.md#std-label-changeStreams) on a collection named `cakeSales` that you will see later in this section: [source]
- To monitor the `cakeSales` collection changes, use `cakeSalesCursor`. For example, to obtain the next document from `cakeSalesCursor`, use the [`next()`](https://www.mongodb.com/docs/manual/reference/method/cursor.next.md#mongodb-method-cursor.next) method: [source]
- To set the retry count at startup, use the [`security.ldap.retryCount`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-security.ldap.retryCount) configuration file option. [source]
- To access documents in a cursor, you can manually iterate the cursor or use the [`toArray()`](https://www.mongodb.com/docs/manual/reference/method/cursor.toarray.md#mongodb-method-cursor.toArray) method. [source]
- To create a change stream cursor using the aggregation stage, run the [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) command. [source]
- To open the cursor, run `cur`. [source]
- Use changes in this value to calculate the rate at which the process opens change stream cursors. A consistently high rate can indicate that applications resume change streams more often than expected. [source]
- To access the returned documents with a driver, use the appropriate cursor handling mechanism for the [driver language.](https://www.mongodb.com/docs/drivers/) [source]
- To manually iterate over the results, assign the returned cursor to a variable with the `var` keyword, as shown in the following sections. [source]
- To return one document from a time series collection, you can use the `findOne()` method. This returns a [cursor.](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) [source]
- To return one document from a time series collection, you can use the `find_one()` method. This returns a [cursor.](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) [source]
- To specify an initial batch size for the cursor, use the following syntax for the `cursor` option: [source]
- To specify batch size for subsequent [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) operations, use [`batchSize()`](https://www.mongodb.com/docs/manual/reference/method/cursor.batchsize.md#mongodb-method-cursor.batchSize) in mongosh or the `batchSize` field in the [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) command. [source]
- To learn more about MAX TIME MS, see [cursor.maxTimeMS()](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS/) in the MongoDB manual. [source]
- Use the `disableBlockWarnings()` cursor option to silence warnings that `mongosh` prints when you run blocking calls on cursors, such as `.next()` or `.hasNext()` on change streams and tailable cursors. [source]
- Create a change stream cursor to monitor changes to `myCollection` using [`db.collection.watch()`:](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#mongodb-method-db.collection.watch) [source]
- Set the `fullDocument` option to `"updateLookup"` to direct the change stream cursor to lookup the most current majority-committed version of the document associated to an update change stream event. [source]
- To learn how to iterate through documents in a cursor, see your [driver's documentation](https://www.mongodb.com/docs/drivers/). If you are using `mongosh`, see [Iterate a Cursor in `mongosh`.](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#std-label-read-operations-cursors) [source]
- Create a cursor variable named `sensorCursor` that reads the documents from the `sensor` collection: [source]
Examples and snippets
- ```javascript — `metrics : {` … [source]
- ```javascript — `uri : 'statistics:',` … [source]
- ```javascript — `db.runCommand(` … [source]
- ```javascript — `db.restaurants.find( { _id: 5 } ).readConcern("linearizable").maxTimeMS(10000)` … [source]
- ```javascript — `db.movies.aggregate(` … [source]
- ```c — `/* Make a new session, session2, and make it causally-consistent` … [source]
- ```javascript — `"ns" : <string>,` … [source]
- ```javascript — `db.runCommand( {` … [source]
- ```javascript — `db.runCommand(` … [source]
- ```javascript — `ok: 1,` … [source]
- ```javascript — `ok: 1,` … [source]
- ```text — `"explainVersion": "1",` … [source]
- ```java — `var explainCommand = new Document("explain", new Document()` … [source]
- ```javascript — `const explainResult = await database.command({` … [source]
- ```python — `explain_result = database.command(` … [source]
- ```javascript — `db.collection.find( { a: 5, b: 5 } ).count()` … [source]
- ```javascript — `db.orders.find(` … [source]
- ```javascript — `db.movies.countDocuments( {}, { hint: { rated: 1 } } )` … [source]
- ```javascript — `db.movies.countDocuments()` … [source]
- ```javascript — `"type" : "idleSession",` … [source]
- ```javascript — `"shard" : "shardB",` … [source]
- ```swift — `let options = ClientSessionOptions(causalConsistency: true)` … [source]
- ```csharp — `// Indexes on ``timeField`` descending are more performant because they` … [source]
- ```java — `// Indexes on ``timeField`` descending are more performant because they` … [source]
- ```javascript — `// Indexes on ``timeField`` descending are more performant because they` … [source]
- ```python — `# Indexes on ``timeField`` descending are more performant because they` … [source]
- ```javascript — `{ $substrCP: [ <string expression>, <code point index>, <code point count> ] }` … [source]
- ```javascript — `db.movies.explain().count( { year: { $gt: 2000 } } )` … [source]
- ```javascript — `var cursor = db.users.find(` … [source]
- ````text — `## Summary` … [source]
- [ — `{ "$match": { "borough": "Manhattan", "cuisine": "Italian" } },` … [source]
- ```javascript — `"t":{"$date":"2026-08-14T13:36:19.194-04:00"},"s":"D1",` … [source]
- ```javascript — `{ $substrBytes: [ <string expression>, <byte index>, <byte count> ] }` … [source]
- ```javascript — `db.runCommand(` … [source]
- ```javascript — `db.runCommand(` … [source]
- ```javascript — `db.adminCommand( {` … [source]
- ```javascript — `"t":{` … [source]
- ```javascript — `"_id": { "client": "192.0.2.10", "user": ["appUser"], "ns": "db1.collA" },` … [source]
- ```shell — `_id: 1,` … [source]
- ```javascript — `db.movies.aggregate([` … [source]
- ```javascript — `_id: null,` … [source]
- ```sql — `SELECT COUNT(*) AS count FROM movies` … [source]
- ```javascript — `{ _id: 1909, totalRuntime: 14, averageRuntime: 14, count: 1 },` … [source]
- ```sql — `SELECT year,` … [source]
- ```javascript — `db.movies.aggregate([` … [source]
- ```javascript — `_id: null,` … [source]
- ```sql — `SELECT Sum(runtime) AS totalRuntime,` … [source]
- ```javascript — `db.collection.countDocuments( <query>, <options> )` … [source]
- ```javascript — `db.collection.aggregate( [` … [source]
- ```javascript — `db.runCommand( { count: 'orders' } )` … [source]
- ```javascript — `db.runCommand( { count:'orders',` … [source]
- ```javascript — `db.runCommand( { count:'orders',` … [source]
- ```python — `cursor = db.inventory.find({"item": "canvas"})` … [source]
- ```javascript — `db.adminCommand( {` … [source]
- ```javascript — `const db = client.db("admin");` … [source]
- ```javascript — `const db = client.db("admin");` … [source]
- ```javascript — `"command" : {` … [source]
- ```javascript — `ok: 1,` … [source]
- ```javascript — `ok: 1,` … [source]
- ```javascript — `{ $count: <string> }` … [source]
- ```javascript — `db.movies.aggregate( [` … [source]
- ```javascript — `$collStats:` … [source]
- ```javascript — `{ "ns" : "test.matrices",` … [source]
- ```javascript — `localTime : 2020-03-06T01:44:57.437Z,` … [source]
- ```javascript — `db.matrices.aggregate( [ { $collStats: { count: { } } } ] )` … [source]
- ```javascript — `"ns" : "test.matrices",` … [source]
- ```javascript — `"ns" : "test.matrices",` … [source]
- ```javascript — `db.runCommand(` … [source]
- ```javascript — `"cursor" : {` … [source]
- ```javascript — `db.collection.find({...}).collation({...}).sort({...});` … [source]
- ```none — `{ $count: { } }` … [source]
- ```bash — `mongod --setParameter cursorTimeoutMillis=300000` … [source]
- ```javascript — `db.adminCommand( { setParameter: 1, cursorTimeoutMillis: 300000 } )` … [source]
- ```none — `_id: <uuid>,` … [source]
- ```javascript — `ns: 'sample_mflix.nonExistentCollection',` … [source]
- ```javascript — `db.movies.aggregate( [` … [source]
- ```javascript — `categorizedByGenres: [` … [source]
- ```text — `cursor: {` … [source]
- ```javascript — `{ "_id" : 0.75, "count" : 1 }` … [source]
- ```javascript — `db.users.aggregate(` … [source]
- ```javascript — `db.collection.aggregate(` … [source]
- ```javascript — `try {` … [source]
- ```json — `indexBulkBuilder: {` … [source]
- ```json — `indexStats: {` … [source]
- ```javascript — `opcounters : {` … [source]
- ```javascript — `opcountersRepl : {` … [source]
- ```javascript — `querySettings: {` … [source]
- ```javascript — `spillWiredTiger: {` … [source]
- ```bash — `var session = db.getMongo().startSession()` … [source]
- ```json — `"cursor": {` … [source]
- ```javascript — `cursor: {` … [source]
- ```javascript — `{ _id: { min: 2, max: 5 }, count: 1 },` … [source]
- ```javascript — `db.inventory.find().batchSize(10)` … [source]
- ```javascript — `{ $group: { _id: <expression>, count: { $sum: 1 } } },` … [source]
- ```javascript — `{ _id: "painting", count: 6 },` … [source]
- ```javascript — `const pipeline = [` … [source]
- ```javascript — `for await (const document of cursor) {` … [source]
- ```python — `pipeline = [` … [source]
- ```python — `for doc in cursor:` … [source]
- ```javascript — `cursor.comment( <string> )` … [source]
- ```javascript — `db.artists.aggregate( [` … [source]
- ```javascript — `{ "_id" : 1840, "count" : 1, "artists" : [ { "name" : "Odilon Redon", "year_born" : 1840 } ] }` … [source]
- ```javascript — `{ "_id" : 1860, "count" : 4, "artists" :` … [source]
- ```javascript — `db.artwork.aggregate( [` … [source]
- ```javascript — `"price" : [ // Output of first facet` … [source]
- ```python — `cursor = db.inventory.find({"status": "A"})` … [source]
- ```python — `cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1})` … [source]
- ```python — `cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "_id": 0})` … [source]
- ```python — `cursor = db.inventory.find({"status": "A"}, {"status": 0, "instock": 0})` … [source]
- ```python — `cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "size.uom": 1})` … [source]
- ```python — `cursor = db.inventory.find({"status": "A"}, {"size.uom": 0})` … [source]
- ```javascript — `const cursor = db.collection('inventory').find({` … [source]
- ```javascript — `const cursor = db` … [source]
- ```javascript — `const cursor = db` … [source]
- ```javascript — `const cursor = db` … [source]
- ```javascript — `const cursor = db` … [source]
- ```php — `$cursor = $db->inventory->find(['status' => 'A']);` … [source]
- ```javascript — `db.placesView.countDocuments( { category: "cafe" } )` … [source]
- ```javascript — `"_id" : {` … [source]
- ```javascript — `"area" : [` … [source]
- ```javascript — `try {` … [source]
- ```javascript — `db.collection.findAndModify({` … [source]
- ```javascript — `db.books.aggregate([` … [source]
- ```javascript — `db.adminCommand( {` … [source]
- ```javascript — `key: {` … [source]
- ```javascript — `key: {` … [source]
- ```javascript — `try {` … [source]
- ```javascript — `"inprog": [` … [source]
- ```javascript — `shard: '<string>',` … [source]
- ```javascript — `const cursor = collection.find({` … [source]
- ```javascript — `{ _id: { year: 1939, rated: 'PASSED' }, count: 1 },` … [source]
- ```javascript — `{ _id: { year: 1939, rated: 'PASSED' }, count: 1 },` … [source]
- ```javascript — `db.comments.aggregate([` … [source]
- ```javascript — `[ { _id: '1970-01', count: 71 } ]` … [source]
- ```javascript — `const pipeline = [` … [source]
- ```javascript — `cursor.returnKey()` … [source]
- ```javascript — `cursor.tailable( { awaitData : <boolean> } )` … [source]
- ```json — `"type" : "op",` … [source]
- ```javascript — `db.collection.find(<query>).count()` … [source]
- ```javascript — `db.orders.find().count()` … [source]
- ```javascript — `db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()` … [source]
- ```javascript — `db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).limit(5).count(true)` … [source]
- ```javascript — `db.collection.find({description: /August [0-9]+, 1969/}).maxTimeMS(50)` … [source]
- ```javascript — `var t = db.myCappedCollection;` … [source]
- ```javascript — `db.collection.find(<query>).noCursorTimeout()` … [source]
Measurements and reference values
- | Chart | Description | | --- | --- | | Connections | Number that indicates the total active connections to the cluster. Monitor connections to determine whether the current connection limits are sufficient. If necessary, scale the cluster tier. To learn more, see [Fix Connection Issues](https://www.mongodb.com/docs/atlas/reference/alert-resolutions/connection-alerts.md#std-label-connection-alerts) and [Fix Lost Primary.](https://www.mongodb.com/docs/atlas/reference/alert-resolutions/no-primary.md#std-label-no-primary) Use [`$currentOp`](https://www.mongodb.com/docs/manual/reference/operator/a [source]
- $sample uses a pseudo-random cursor only if it is the first pipeline stage, N is under 5% of the collection (threshold not configurable), and the collection has more than 100 documents. Otherwise it reads all input and does a top-k random sort, which is subject to sort memory limits and can spill to disk. On a view $sample is never first, so it always scans. [source]
- If your use case requires a uniform sample, avoid the pseudo-random cursor. To do so, run $sample after another stage, or set N to more than 5% of the documents in the collection. [source]
- If your use case requires a uniform sample, avoid the pseudo-random cursor. To do so, run [`$sample`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) after another stage, or set `N` to more than 5% of the documents in the collection. [source]
- `$changeStreamSplitLargeEvent` splits events that exceed 16 MB into fragments and returns the fragments sequentially using the change stream cursor. [source]
- estimatedDocumentCount() can be inaccurate after an unclean shutdown (drift depends on writes since the last checkpoint, usually 60 s) and on a sharded cluster does not filter orphaned documents; running validate on each collection restores the count statistic. [source]
Problems, failure modes and limitations
- | Field | Type | Literal or Normalized | Description | | --- | --- | --- | --- | | `key` | Document | Literal | Contains the query shape and additional query attributes that group a set of queries together | | `key.queryShape` | Document | Literal | Contains attributes used to group similar queries together. For more information, see [Query Shape.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/querystats.md#std-label-queryStats-queryShape) | | `key.client` | Document | Literal | Describes client information associated with the key | | `key.client.application` | Document | [source]
- | Field | Type | Description | | --- | --- | --- | | `count` | string | The name of the collection or view to count. | | `query` | document | Optional. A query that selects which documents to count in the collection or view. | | `limit` | integer | Optional. The maximum number of matching documents to return. | | `skip` | integer | Optional. The number of matching documents to skip before returning results. | | `hint` | string or document | Optional. The index to use. Specify either the index name as a string or the index specification document. | | `readConcern` | document | Optional. Specifi [source]
- | Method | Availability | Description | | --- | --- | --- | | Use the Atlas Performance Advisor | M10+ Atlas clusters | The Atlas Performance Advisor monitors slow queries and suggests new indexes to improve performance. For more information, see [Monitor and Improve Slow Queries with the Performance Advisor.](https://www.mongodb.com/docs/atlas/performance-advisor.md#std-label-performance-advisor) | | Check ongoing operations in Atlas | M10+ Atlas clusters | You can use the [Atlas Real-Time Performance Panel](https://www.mongodb.com/docs/atlas/real-time-performance-panel.md#std-label-real-time [source]
- | Name | Type | Required | Description | | --- | --- | --- | --- | | --clusterName | string | true | Human-readable label that identifies the cluster. | | --commands | & | false | Retrieve query shape statistics matching specified MongoDB commands. To include multiple commands, pass the parameter multiple times delimited with an ampersand (&) between each command. The currently supported parameters are: find, distinct, aggregate, count, insert, update, and delete. The insert, update, and delete commands return results only for clusters running MongoDB 9.0 or later with write query shape statis [source]
- MongoDB does not count network latency between the client and the server towards a cursor's time limit. For a sharded cluster, however, MongoDB does include the latency between the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) and [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instances towards this time limit. [source]
- To detect a broadcast: run explain('executionStats') through mongos and check whether the shards array lists every shard or the top stage is SHARD_MERGE. Also check the mongos slow query log for nShards equal to total shard count. A targeted query shows one or a few shards (SINGLE_SHARD for one). [source]
- | Matching Policy | Description | | --- | --- | | `"automatic"` (Default) | Starting in 5.0, `"automatic"` is the new default value. When set for a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), the instance follows the behavior specified for the `"matchPrimaryNode"` option. When set for a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod), the instance follows the behavior specified for the `"disabled"` option. WARNING: If the [`ShardingTaskExecutorPoolReplicaSetMatching`](https://www.mo [source]
- | Field | Type | Description | | --- | --- | --- | | `limit` | integer | Optional. The maximum number of documents to count. | | `skip` | integer | Optional. The number of documents to skip before counting. | | `hint` | string or document | Optional. An index name or the index specification to use for the query. | | `maxTimeMS` | integer | Optional. The maximum amount of time to allow the count to run. | [source]
- | Name | Type | Required | Description | | --- | --- | --- | --- | | --duration | int | false | Length of time expressed during which the query finds suggested indexes among the managed namespaces in the cluster. This parameter expresses its value in milliseconds. If you don't specify the **since** parameter, the endpoint returns data covering the duration before the current time.; If you specify neither the **duration** nor **since** parameters, the endpoint returns data from the previous 24 hours. | | --envelope | envelope | false | Flag that indicates whether Application wraps the response [source]
- If the above conditions are not met, MongoDB cannot use the wildcard index for the sort. MongoDB does not support [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) operations that require a different index from that of the query predicate. [source]
- | Method | Availability | Description | | --- | --- | --- | | Use the Atlas Query Profiler | M10+ Atlas clusters | The Atlas Query Profiler shows long-running operations and performance statistics. For more information, see [Monitor Query Performance with the Query Profiler.](https://www.mongodb.com/docs/atlas/tutorial/query-profiler.md#std-label-profile-database) | | Enable the Database Profiler | Atlas clusters and self-hosted deployments | When enabled, the database profiler stores information about slow queries in the [`system.profile`](https://www.mongodb.com/docs/manual/reference/system- [source]
- By default the first batch of a find or aggregate is the lesser of 101 documents or 16 MiB; later getMore batches have no document-count default and are capped at 16 MiB. A set batchSize can only lower the limit below 16 MiB, never raise it. [source]
- maxTimeMS is a cumulative server-side processing limit for a cursor. The server terminates the operation like killOp, and only at an interrupt point. It is unrelated to idle time (noCursorTimeout). Client-to-server latency is not counted, but in a sharded cluster mongos-to-mongod latency is. [source]
- On getMore, maxTimeMS applies per call. For a tailable awaitData cursor it equals maxAwaitTimeMS (how long to wait for new documents). For a non-tailable cursor a timeout raises an error. [source]
- You cannot use [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) and shell helpers [`cursor.count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) and `count()` in [transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions-ops-count) [source]
- distinct operations can use indexes and can be covered by them. For array fields distinct treats each array element as a separate value. On sharded clusters distinct may return orphaned documents; on time series collections it cannot use indexes efficiently and the docs say to use $group; in transactions on sharded collections distinct is not allowed and $group must be used. [source]
- | Field | Type | Literal or Normalized | | --- | --- | --- | | `key.queryShape.collation` | Document | Normalized | | `key.queryShape.query` | Document | Normalized | | `key.queryShape.limit` | Integer | Normalized | | `key.queryShape.skip` | Integer | Normalized | [source]
- | Option | Description | | --- | --- | | `allHosts` | Configures how the `$planCacheStats` aggregation stage targets nodes in a sharded cluster. If `true`, [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) broadcasts the `$planCacheStats` aggregation stage to all nodes (primary and secondaries) for each affected shard that contains one or more chunks from the target collection.; If `false`, the `$planCacheStats` aggregation stage follows the [Read Preference](https://www.mongodb.com/docs/manual/core/read-preference.md#std-label-read-preference) and [source]
- The above unsupported index types are ignored by the query planner in strict mode. For example, attempting to use a sparse index with cursor.hint() results in the following BadValue error: [source]
- hasSortStage is a boolean that is true when a query cannot use the ordering in the index to return the requested sorted results; i.e. MongoDB must sort the documents after it receives the documents from a cursor. The field only appears when the value is true. [source]
- - If a query includes a `$text` expression, you cannot use [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) to specify which index to use for the query. [source]
- System indexes are not limited to `maxNumActiveUserIndexBuilds`, however a system index build counts against the limit for user index builds. [source]
- - If you use [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) on a [hidden index](https://www.mongodb.com/docs/manual/core/index-hidden.md) or an index that doesn't exist, the operation returns an error. [source]
- Due to the unique data structure of time series collections, MongoDB can't efficiently index them for distinct values. Avoid using the [`distinct`](https://www.mongodb.com/docs/manual/reference/command/distinct.md#mongodb-dbcommand-dbcmd.distinct) command or [`db.collection.distinct()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#mongodb-method-db.collection.distinct) helper method on time series collections. Instead, use a [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) aggregation to group [source]
- | Field | Type | Description | | --- | --- | --- | | `string expression` | string | The string from which the substring will be extracted. `string expression` can be any valid [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) as long as it resolves to a string. For more information on expressions, see [Expressions.](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) If the argument resolves to a value of `null` or refers to a field that is missing, [`$substrCP`](https://www.mongodb.c [source]
- - The above unsupported index types are ignored by the [query planner](https://www.mongodb.com/docs/manual/core/query-plans.md#std-label-query-plans-query-optimization) in [strict mode](https://www.mongodb.com/docs/manual/reference/stable-api.md#std-label-stable-api-strict-client). For example, attempting to use a `sparse` index with [`cursor.hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) results in the following `BadValue` error: [source]
- | Field | Type | Description | | --- | --- | --- | | `createIndexes` | string | The collection for which to create indexes. | | `indexes` | array | Specifies the indexes to create. Each document in the array specifies a separate index. | | `writeConcern` | document | Optional. A document expressing the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern.md). Omit to use the default write concern. | | `commitQuorum` | integer or string | Optional. The minimum number of data-bearing replica set members (i.e. commit quorum), including the primary, that must report a succes [source]
- - If the pipeline contains stages after `$group` that cannot be executed using the slot-based execution engine, the `queryPlanner` object is in `explain.stages[0].$cursor.queryPlanner`. [source]
- - If the pipeline contains stages after `$lookup` that cannot be executed using the slot-based execution engine, the `queryPlanner` object is in `explain.stages[0].$cursor.queryPlanner`. [source]
- It is important to be mindful of the content in the `string expression` because providing a `byte index` or `byte count` located in the middle of a UTF-8 character will result in an error. [source]
- You cannot cursor.hint() a hidden index. [source]
- If a sparse index would result in an incomplete result set for queries and sort operations, MongoDB will not use that index unless a [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) explicitly specifies the index. See [Sparse Index On A Collection Cannot Return Complete Results](https://www.mongodb.com/docs/manual/core/index-sparse.md#std-label-sparse-index-incomplete-results) for an example. [source]
- | Field | Type | Description | | --- | --- | --- | | [setIndexCommitQuorum](https://www.mongodb.com/docs/manual/reference/command/setindexcommitquorum.md#std-label-setIndexCommitQuorum-cmd-coll) | `string` | The name of the collection for which the indexes are being built. | | [indexNames](https://www.mongodb.com/docs/manual/reference/command/setindexcommitquorum.md#std-label-setIndexCommitQuorum-cmd-indexNames) | `array` | An array of in-progress index builds to modify. Each element of the array must be the *name* of the index. The indexes specified to `indexNames` must be the entire set of i [source]
- | Name | Type | Required | Description | | --- | --- | --- | --- | | --envelope | envelope | false | Flag that indicates whether Application wraps the response in an envelope JSON object. Some API clients cannot access the HTTP response headers or status code. To remediate this, set envelope=true in the query. Endpoints that return a list of results use the results object as an envelope. Application adds the status parameter to the response body. | | --groupId | string | true | Unique 24-hexadecimal digit string that identifies your project. Use the [/groups](#tag/Projects/operation/listProjec [source]
- You cannot use the following query operators as part of the query expression for `countDocuments()`: [source]
- Prior to MongoDB 7.0, [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural) accepts incorrect type values, such as `0`, `NaN`, "X", and `-0.01`. After MongoDB 7.0, if you pass any value other than `1` and `-1` to [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural), MongoDB returns an error. [source]
- Only queries that match a large number of documents reach the limit. To reduce the memory that the query requires, specify `maxDistance` to restrict the search area. This memory counts toward the per-operation memory limit. To learn more, see [Per-Operation Memory Limit.](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#std-label-operation-memory-limit) [source]
- If the `$lookup` query on a shard can perform a local read, the `$lookup` doesn't record a separate operation for querying the foreign collection. A local read refers to when the query on the foreign collection targets only the same shard where the current operation is being executed. As a result, the `$lookup` operation increases the `$collStats` latency metrics and operation counts, but does not generate a slow query log for the foreign collection. [source]
- - Queries with `$text` cannot use [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural) sort. [source]
- | Field | Type | Description | | --- | --- | --- | | `getMore` | long | The cursor identifier. | | `collection` | string | The name of the collection over which the cursor is operating. | | `batchSize` | positive integer | Optional. The maximum number of documents returned for each batch. If `batchSize` is not set, `getMore` returns up to 16 mebibytes (MiB) for each batch. If `batchSize` is set, `getMore` returns the lesser of `batchSize` documents or 16 MiB. | | `maxTimeMS` | non-negative integer | Optional. Specifies how long the server waits for new documents matching a [tailable cursor](ht [source]
- For cursors created inside a session, you cannot call `getMore` outside the session. [source]
- For cursors created outside a session, you cannot call `getMore` inside a session. [source]
- - For cursors created outside of a transaction, you cannot call [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) inside the transaction. [source]
- - For cursors created in a transaction, you cannot call [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) outside the transaction. [source]
- Starting in MongoDB 8.2, the cursor identifier must match the name of the cursor operating on the specified `collection`. If no matching cursor exists, `getMore` returns an error. [source]
- The [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) command can either return a cursor or store the results in a collection. Each document in the result set is subject to the 16 mebibyte [BSON Document Size limit](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-BSON-Document-Size). If any single document exceeds the [BSON Document Size limit](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-BSON-Document-Size), the aggregation produces an error. The limit only applies to the returned [source]
- For a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instance, the command enables, disables, or configures the [database profiler](https://www.mongodb.com/docs/manual/tutorial/manage-the-database-profiler.md#std-label-database-profiler). The profiler captures and records data on the performance of write operations, cursors, and database commands on a running [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instance. If the profiler is disabled, the command configures how slow operations [source]
- The following example sets [`replBatchLimitBytes`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.replBatchLimitBytes) to 64 MB to limit the oplog application batch size: [source]
- The count of open transactions is server-wide. Process-internal transactions are exempt from rejection, but still contribute to the total count when the server enforces the limit for external clients. [source]
- - For sharded collections, you cannot use the [`db.collection.distinct()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#mongodb-method-db.collection.distinct) method or the [`distinct`](https://www.mongodb.com/docs/manual/reference/command/distinct.md#mongodb-dbcommand-dbcmd.distinct) command. [source]
- This method, [`maxAwaitTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxawaittimems.md#mongodb-method-cursor.maxAwaitTimeMS), sets a limit on how long a [tailable cursor](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) waits for the next response. [`maxTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxtimems.md#mongodb-method-cursor.maxTimeMS) sets a limit on total processing time. [source]
- A negative limit is similar to a positive limit but closes the cursor after returning a single [batch](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursor-batches) of results. As such, with a negative limit, if the limited result set does not fit into a single batch, the number of documents received will be less than the specified limit. By passing a negative limit, the client indicates to the server that it will not ask for a subsequent batch via `getMore`. [source]
- Specifies a time limit in milliseconds. If you do not specify a value for maxTimeMS, operations will not time out. A value of 0 explicitly specifies the default unbounded behavior. [source]
- For sharded collections, you cannot use the db.collection.distinct() method or the distinct command. [source]
- - Specify a global default time limit for all queries. The [`defaultMaxTimeMS`](https://www.mongodb.com/docs/manual/reference/cluster-parameters/defaultmaxtimems.md#mongodb-parameter-param.defaultMaxTimeMS) cluster parameter specifies a default time limit for individual read operations to complete, and applies to all queries that do not include the [`maxTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxtimems.md#mongodb-method-cursor.maxTimeMS) option. If a query specifies a `maxTimeMS()` option, that value overrides the `defaultMaxTimeMS` value. [source]
- | Metric | Description | | --- | --- | | `numBuckets` | The total number of tracked buckets. Expected to be equal to the sum of `numOpenBuckets` and `numArchivedBuckets`. | | `numOpenBuckets` | The number of tracked buckets with a full representation stored in-cache, ready to receive new documents. | | `numIdleBuckets` | The number of buckets that are open and currently without an uncommitted document insertion pending. A subset of numOpenBuckets. | | `numArchivedBuckets` | The number of tracked buckets with a minimal representation stored in-cache that can be efficiently reopened to receive n [source]
- The number of times a change stream cursor encountered a fatal, non-resumable error. For example, this counter increments when a pipeline stage removes the `_id` field from change stream events. [source]
- The total number of cursors that have timed out since the server process started. If this number is large or growing at a regular rate, this may indicate an application error. [source]
- `opQuery` counts the number of requests for opcodes that are deprecated in MongoDB 5.0 but are temporarily supported. This section only appears in the `db.serverStatus()` output when a deprecated opcode has been used. [source]
- While MongoDB doesn't have a limit on the number of batch operations it can perform, it allows a maximum of 100,000 [writes](https://www.mongodb.com/docs/manual/reference/mql/crud-commands.md#std-label-query-and-write-commands) in a single batch operation. A single batch refers to a single request to the server. If the number of writes in a batch operation exceeds 100,000, the client driver divides the batch into smaller groups with counts less than or equal to 100,000. [source]
- Consider an application that issues a [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find). The server returns a cursor along with a batch of documents defined by the [`cursor.batchSize()`](https://www.mongodb.com/docs/manual/reference/method/cursor.batchsize.md#mongodb-method-cursor.batchSize) of the [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find). The session refreshes each time the application requests a new batch of documents from the se [source]
- Verify that documents remain within the size limit. Encrypted values and their metadata count toward the 16 MB [BSON Document Size](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-BSON-Document-Size) limit. [source]
- For cursors created inside a session, you cannot call [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) outside the session. [source]
- Similarly, for cursors created outside of a session, you cannot call [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) inside a session. [source]
- The maximum number of documents that can be returned in each batch of a query result. By default, the initial batch size is the lesser of `101` documents or 16 mebibytes (MiB) worth of documents. Subsequent batches have a maximum size of 16 MiB. This option can enforce a smaller limit than 16 MiB, but not a larger one. When set, the `batchSize` is the lesser of `batchSize` documents or 16 MiB worth of documents. [source]
- | Field | Type | Description | | --- | --- | --- | | `size` | integer | The maximum number of documents that can be returned in each batch of a query result. The default initial batch size is the lesser or `101` documents or 16 mebibytes (MiB) worth of documents. Subsequent batches have a maximum size of 16 MiB. This option can enforce a smaller limit than 16 MiB, but not a larger one. The default applies to drivers and Mongo Shell. For details, see [Cursor Batches.](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursor-batches) | [source]
- | Field | Type | Description | | --- | --- | --- | | [groupBy](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#std-label-bucket-group-by) | expression | An [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) to group documents by. To specify a [field path](https://www.mongodb.com/docs/manual/core/aggregation-pipeline.md#std-label-agg-quick-ref-field-paths), prefix the field name with a dollar sign `$` and enclose it in quotes. Unless [`$bucket`](https://www.mongodb.com/docs/manual/reference/operator/aggre [source]
- Limit stages, counted separately by limit value. limitSmall counts limits of 100 or less, limitMedium counts limits from 101 to 10,000, and limitLarge counts limits greater than 10,000. [source]
- The `{ cursor: { batchSize: 0 } }` document specifies the size of the *initial* batch size and indicates an empty first batch. This quickly returns a cursor or failure message without doing significant server-side work. [source]
- - This pipeline cannot directly access the fields from the results document. To access the `count` field in the results document, the pipeline uses the `$$new` variable; i.e. `$$new.count`. [source]
- Specifies a cumulative time limit in milliseconds for processing operations on a cursor. [source]
- | Parameter | Type | Description | | --- | --- | --- | | `milliseconds` | integer | Specifies a cumulative time limit in milliseconds for processing operations on the cursor. | [source]
- MongoDB targets operations for termination if the associated cursor exceeds its allotted time limit. MongoDB terminates operations that exceed their allotted time limit using the same mechanism as [`db.killOp()`](https://www.mongodb.com/docs/manual/reference/method/db.killop.md#mongodb-method-db.killOp). MongoDB only terminates an operation at one of its designated [interrupt points.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-interrupt-point) [source]
- Queries that generate multiple batches of results continue to return batches until the cursor exceeds its allotted time limit. [source]
- Depending on the number of changes applied during the update operation and the size of the full document, there is a risk that the size of the change event document for an update operation is greater than the 16MB BSON document limit. If this occurs, the server closes the change stream cursor and returns an error. [source]
- Starting in v3.2, the `cursor.addOption()` operator is deprecated in [`mongo`](https://www.mongodb.com/docs/manual/reference/mongo.md#mongodb-binary-bin.mongo). Use available [cursor methods](https://www.mongodb.com/docs/manual/reference/method.md#std-label-doc-cursor-methods) instead. [source]
- You cannot apply cursor methods to the result of `findOne()` because a single document is returned. You have access to the document directly: [source]
Comparisons and alternatives
- On a sharded cluster each shard samples independently and mongos samples the merged result. SERVER-68623 (closed Won't Do, 2022-09-28) reports each shard gets the full requested size and so picks random sort instead of the cursor, because a mongod does not know the cluster-wide document count; the 5% rule is documented only for mongod behaviour. [source]
- | Field | Field Type | Necessity | Description | | --- | --- | --- | --- | | `setQuerySettings` | document or string | Required | You can provide either: The same fields as those in a [`find`](https://www.mongodb.com/docs/manual/reference/command/find.md#mongodb-dbcommand-dbcmd.find), [`distinct`](https://www.mongodb.com/docs/manual/reference/command/distinct.md#mongodb-dbcommand-dbcmd.distinct), or [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) command, and a `$db` field with the database associated with the original command [source]
- The total number of cursors that have been opened since [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) started, including cursors currently open. Differs from [`metrics.cursor.open.total`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.cursor.open.total), which is the number of currently open cursors only. [source]
- An aggregation starting with $sort then $group using $first or $last can run as a DISTINCT_SCAN (loose index scan) that reads one index entry/document per group, provided a matching index exists and the group fields are not multikey; the author's 10-group example examined 10 documents versus about 200,000 index rows for PostgreSQL DISTINCT ON. [source]
- | Field | Type | Description | | --- | --- | --- | | dropIndexes | String | The name of the collection whose indexes to drop. | | index | string or document or array of strings | The index or indexes to drop. To drop all indexes except the `_id` index and the last remaining shard key index from the collection if one exists, specify `"*"`.; To drop a single index, specify either the index name, the index specification document (unless the index is a [text](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-type-text) index), or an array of the index name. [source]
- `cursor.explain()` defaults to `queryPlanner`, unlike the [`explain`](https://www.mongodb.com/docs/manual/reference/command/explain.md#mongodb-dbcommand-dbcmd.explain) command, which defaults to `allPlansExecution`. [source]
- Modifies the cursor to return index keys rather than the documents. [source]
- Unlike [`db.collection.count()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#mongodb-method-db.collection.count), `countDocuments()` does not use the metadata to return the count. Instead, it performs an aggregation of the document to return an accurate count, even after an unclean shutdown or in the presence of [orphaned documents](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-orphaned-document) in a sharded cluster. [source]
- The flag that indicates whether the [tailable cursor](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) should temporarily block a [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) command on the cursor while waiting for new data rather than returning no data. [source]
- | Field Name | Description | | --- | --- | | `latencyStats` | Adds [latency statistics](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#std-label-latency-stats-document) to the return document. | | `latencyStats.histograms` | Adds latency histogram information to the embedded documents in `latencyStats` if `true`. | | `storageStats` | Adds [storage statistics](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#std-label-storage-stats-document) to the return document. Specify an empty document (i.e. `storageStats: {}`) to use the defa [source]
- | Field Name | Description | | --- | --- | | `ns` | The [namespace](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-namespace) of the requested collection or view. | | `shard` | The name of the shard the output document corresponds to. Only present when `$collStats` runs on a sharded cluster. Both [sharded and non-sharded collections](https://www.mongodb.com/docs/manual/sharding.md#std-label-sharded-vs-non-sharded-collections) will produce this field. | | `host` | The hostname and port of the `mongod` process which produced the output document. | | `localTime` | The current [source]
- If an exact number of documents is required from each run, the [`$sample`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) operator should be used instead of `$sampleRate`. [source]
- | Metric | Description | | --- | --- | | `totalPass` | Total number of deletion passes completed by the purging job. | | `docsDeleted` | Cumulative number of pre-image documents deleted by the purging job. **Changed in version 9.0** Starting in MongoDB 9.0, when size and count information is not available for the `config.system.preimages` collection, MongoDB reports this value as an estimate rather than an exact count. | | `bytesDeleted` | Cumulative size in bytes of all deleted documents from all pre-image collections by the purging job. **Changed in version 9.0** Starting in MongoDB 9.0, whe [source]
- The total number of oplog entries applied. The [`metrics.repl.apply.batchSize`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.repl.apply.batchSize) is incremented with the number of oplog entries in a batch at the batch boundaries instead of being incremented by one after each entry. [source]
- The total number of cursors that have been opened since the server process started, including cursors currently open. Differs from [`metrics.cursor.open.total`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.cursor.open.total), which is the number of currently open cursors only. [source]
- The number of direct shard operations attempted without sufficient authorization. If the operation generates a warning rather than an error, `unauthorizedDirectShardOps` might count it more than once. [source]
- The [`$strLenBytes`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/strlenbytes.md#mongodb-expression-exp.-strLenBytes) operator differs from [`$strLenCP`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/strlencp.md#mongodb-expression-exp.-strLenCP) operator which counts the [code points](http://www.unicode.org/glossary/#code_point) in the specified string regardless of how many bytes each character uses. [source]
- | Parameter | Type | Description | | --- | --- | --- | | `awaitData` | boolean | Optional. For use with [`DBQuery.Option.tailable`](https://www.mongodb.com/docs/manual/reference/method/cursor.addoption.md#mongodb-data-DBQuery.Option.tailable). Sets the cursor to block the query thread when no data is available and await data for a set time instead of immediately returning no data. The cursor returns no data only if the timeout expires. By default, if `maxTimeMS` is set on the command that created the cursor, then the timeout for `awaitData` is the remaining time. Otherwise, the default timeout [source]
- Even though only six hours passed between the two dates, `$dateDiff` returns `1` because the dates fall in different calendar years. This reflects the fact that `$dateDiff` counts unit boundaries crossed rather than elapsed duration. [source]
- The number of documents selected is different each time. If you need to select an exact number of documents, consider using [`$sample`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) instead of `$rand`. [source]
- | Field | Type | Description | | --- | --- | --- | | `resumeAfter` | document | Optional. Directs [`watch()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#mongodb-method-db.collection.watch) to attempt resuming notifications starting after the operation specified in the resume token. Each change stream event document includes a resume token as the `_id` field. Pass the *entire* `_id` field of the change event document that represents the operation you want to resume after. `resumeAfter` is mutually exclusive with `startAfter` and `startAtOperationTime`. | | `star [source]
- Unlike the MongoDB [Drivers](https://www.mongodb.com/docs/drivers/), [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) does not automatically attempt to resume a change stream cursor after an error. The MongoDB drivers make *one* attempt to automatically resume a change stream cursor after certain errors. [source]
- | Flag | Description | | --- | --- | | | Sets the cursor not to close once the last data is received, allowing the query to continue returning data added after the initial results were exhausted. | | | Allows querying of a replica secondary. | | | Prevents the server from timing out idle cursors. | | | For use with [`DBQuery.Option.tailable`](https://www.mongodb.com/docs/manual/reference/method/cursor.addoption.md#mongodb-data-DBQuery.Option.tailable). Sets the cursor to block the query thread when no data is available and await data for a set time instead of immediately returning no data. [source]
- Although similar to the [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method, `findOne()` returns a document rather than a cursor. [source]
Facts and statements
- In a sharded cluster mongos does not forward batchSize to the shards, and later getMore batches return up to 16 MiB per batch regardless of the configured batchSize. [source]
- All metrics in this document are reported on both [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) and [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos). On [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), the `docsExamined` and `bytesRead` counters are aggregated from the shards that serve the change stream. The remaining metrics aren't aggregated from shards and count only the change stream cursors that the [`mongos`](https://www.mongo [source]
- If you use `db.collection.countDocuments()` with an empty query filter, MongoDB performs a full collection scan which can be inefficient. To improve performance, this example specifies a [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) to use the automatically generated `_id` index. Alternatively, you can use a query filter that finds all documents such as `{ "_id": { $gte: MinKey } }` to count all documents using an index. [source]
- MongoDB supports the use of [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) with [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count). See [Specify the Index to Use](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#std-label-count-method-hint) for an example. [source]
- | Metric | Description | | --- | --- | | Execution Count | Number of queries executed per hour which match the query shape. | | Average Execution Time | Average execution time in milliseconds for queries which match the query shape. | | Average Query Targeting | Average number of documents read for every document returned by matching queries. A higher query targeting score indicates a greater degree of inefficiency. For more information on query targeting, see [Query Targeting.](https://www.mongodb.com/docs/atlas/performance-advisor.md#std-label-query-targeting) | | Average Docs Scanned | Aver [source]
- MongoDB can use a wildcard index for satisfying the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) **only if** all of the following are true: [source]
- Assuming that the specified `price` is never an array, MongoDB can use the `product_attributes.$**` wildcard index for satisfying both the [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) and [`sort()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) [source]
- - [`$sample`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) is the first stage of the pipeline. [source]
- - A high number of documents aren't visible to the cursor's transaction. [source]
- ```javascript use admin db.aggregate( [ { $currentOp : { allUsers: true, localOps: true } }, { $match : <filter condition> } // Optional. Specify the condition to find the op. // e.g. { op: "getmore", "command.collection": "someCollection" } ] ) ``` [source]
- Queries that include a sort by [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-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`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural) order can use the `_id` index. [source]
- MongoDB runs the [query optimizer](https://www.mongodb.com/docs/manual/core/query-plans.md#std-label-read-operations-query-optimization) to choose the winning plan for the operation under evaluation. [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) returns the [`queryPlanner`](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.queryPlanner) information for the evaluated method. [source]
- The [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) command uses the `readConcern` level specified in the originating [`find`](https://www.mongodb.com/docs/manual/reference/command/find.md#mongodb-dbcommand-dbcmd.find) command. [source]
- A `readConcern` can be specified for the [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) method [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) using the [`cursor.readConcern()`](https://www.mongodb.com/docs/manual/reference/method/cursor.readconcern.md#mongodb-method-cursor.readConcern) method: [source]
- batchSize changes only how many documents each network round trip fetches. Driver iteration (next, hasNext, for-await) still yields one document at a time from the fetched batch. With batchSize 1 and 1000 results the driver issues 999 getMore calls. [source]
- Too large a batchSize makes the cursor allocate more resources than needed; too small adds network round trips. A batchSize of 0 opens the cursor and returns no documents in the first batch. Third-party sizing ranges (50-200 for large documents or memory limits, 500-2000 for small documents and bulk throughput) are heuristics, not vendor guidance. [source]
- Server sessions idle for 30 minutes expire and the server may kill their cursors, including cursors with noCursorTimeout or a maxTimeMS over 30 minutes. A very large maxTimeMS therefore does not keep a cursor alive. [source]
- From MongoDB 8.2, long-running secondary reads in a sharded cluster can be terminated before orphaned-document cleanup after a chunk migration; the terminateSecondaryReadsOnOrphanCleanup parameter controls this. Long scans on secondaries should expect and retry this. [source]
- Historic bug: in MongoDB 3.0.0-3.0.3, long-running secondary reads did not yield and could stall replication, growing lag and stale reads (SERVER-18190, fixed in 3.0.4). Heavy secondary reads still compete with oplog application for resources. [source]
- MongoDB drivers deprecate their cursor and collection `count()` APIs and use driver-specific APIs that correspond to [`db.collection.countDocuments()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.countdocuments.md#mongodb-method-db.collection.countDocuments) and [`db.collection.estimatedDocumentCount()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimateddocumentcount.md#mongodb-method-db.collection.estimatedDocumentCount). For specific API names, see your driver's API documentation. [source]
- If you use $sample in a sharded cluster, each shard performs the sample operation independently. mongos samples the merged result of each shard's sample operation and returns the requested number of documents. [source]
- Counts the number of documents remaining in a cursor. [source]
- You can chain other cursor methods, such as [`cursor.sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) and [`cursor.count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count), to [`cursor.collation()`:](https://www.mongodb.com/docs/manual/reference/method/cursor.collation.md#mongodb-method-cursor.collation) [source]
- If all of the following conditions are true, [`$sample`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) uses a pseudo-random cursor to select the `N` documents: [source]
- The total number of cursors that have returned more than one batch since [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) started. Additional batches are retrieved using the [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) command. [source]
- The total number of cursors that only target a *single* shard. Only [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances report [`metrics.cursor.open.singleTarget`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.cursor.open.singleTarget) values. [source]
- The total number of cursors that only target *more than one* shard. Only [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances report [`metrics.cursor.open.multiTarget`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.cursor.open.multiTarget) values. [source]
- A document that returns the open cursor count and open session count for the session. [source]
- In sharded clusters, `mongos` does not forward the `batchSize` value to individual shards. Subsequent [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) operations in a sharded cluster return up to 16 MiB of documents per batch, regardless of the configured `batchSize`. [source]
- | Field | Type | Description | | --- | --- | --- | | `maxTimeMS` | integer | Optional. The maximum amount of time to allow the count to run. | [source]
- Counts the number of documents referenced by a cursor. Append the [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) method to a [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) query to return the number of matching documents. The operation does not perform the query but instead counts the results that would be returned by the query. [source]
- The [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) method has the following prototype form: [source]
- The [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) method has the following parameter: [source]
- The following are examples of the [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) method. [source]
- 3. Count the number of documents in the cursor [source]
- 1. Creating a [compound index](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-compound.md#std-label-index-type-compound) on `meta.project` and `meta.type` and supports the aggregation. [source]
- If you use [`min()`](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) with [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) to specify a range: [source]
- - the bound specified by [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) must be greater than the bound specified by [`min()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) [source]
- - The `{ $meta: "indexKey" }` expression is preferred over [`cursor.returnKey()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.returnkey.md#mongodb-method-cursor.returnKey) [source]
- In such cases, during the initial read of the documents, MongoDB pages the documents into memory such that subsequent calls of the same count operation will have better performance. [source]
- dbs.forEach((d) => { if (d.name != 'local') { const listCollCursor = db .getSiblingDB(d.name) .runCommand({ listCollections: 1 }).cursor; [source]
- const collDetails = { db: listCollCursor.ns.split(".$cmd")[0], colls: listCollCursor.firstBatch.map((c) => c.name), }; [source]
- - On a sharded cluster, the resulting count does not correctly filter out [orphaned documents.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-orphaned-document) [source]
- - After an unclean shutdown or [file copy based initial sync](https://www.mongodb.com/docs/manual/core/replica-set-sync.md#std-label-replica-set-initial-sync-file-copy-based), the count may be incorrect. [source]
- For counts based on collection metadata, see also [collStats pipeline stage with the count](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#std-label-collstat-count) option. [source]
- - The [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) specifies **only** the query predicate field. [source]
- - With the `primaryPreferred` read preference, `mongos` can route a retried read to a secondary if the primary indicates overload, even if the primary remains reachable. [source]
- - With the `secondaryPreferred` read preference, `mongos` can route a retried read to the primary if secondaries indicate overload. [source]
- The [`readConcern()`](https://www.mongodb.com/docs/manual/reference/method/cursor.readconcern.md#mongodb-method-cursor.readConcern) method has the following form: [source]
- The [`readConcern()`](https://www.mongodb.com/docs/manual/reference/method/cursor.readconcern.md#mongodb-method-cursor.readConcern) method has the following parameter: [source]
- [`readPref()`](https://www.mongodb.com/docs/manual/reference/method/cursor.readpref.md#mongodb-method-cursor.readPref) does not support the [Read Preference `maxStalenessSeconds`](https://www.mongodb.com/docs/manual/core/read-preference-staleness.md#std-label-replica-set-read-preference-max-staleness) option for read preference. [source]
- The following operation uses the read preference [mode](https://www.mongodb.com/docs/manual/reference/method/cursor.readpref.md#std-label-cursor-readpref-mode) to target the read to a secondary member. [source]
- A document that counts how many internal and external read preference operations the node received while serving as the primary. [source]
- A document that counts how many internal and external read preference operations the node received while serving as a secondary. [source]
- As a cursor returns documents, other operations may run in the background and affect the results, depending on the read concern level. For details, see [Read Isolation, Consistency, and Recency.](https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency.md#std-label-read-isolation-consistency-recency) [source]
- Then, the following example returns those documents whose `location` is at most `0.10` radians from the specified point, ordered from nearest to farthest: [source]
- The following operation uses the index `{ status: 1 }` to count documents in the `orders` collection where the `ord_dt` field is greater than `Date('01/01/2012')` and the `status` field equals `"D"`: [source]
- A string that specifies whether the cursor uses a collection scan (`COLLSCAN`) or an index scan (`IXSCAN { ... }`). [source]
- For a query to use a compound index for a sort, the specified sort direction for all keys in the cursor.sort() document must match the index key pattern or match the inverse of the index key pattern. For example, an index key pattern { a: 1, b: -1 } can support a sort on { a: 1, b: -1 } and { a: -1, b: 1 } but not on { a: -1, b: -1 } or {a: 1, b: 1}. [source]
- | Field Name | Description | | --- | --- | | `total` | The total number of queries that performed a collection scan. | | `nonTailable` | The number of queries that performed a collection scan, but didn't use a [tailable cursor.](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) | [source]
- Specify the `$natural` operator to the [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) method to prevent MongoDB from using *any* index: [source]
- - Query execution stages that buffer records, such as geospatial proximity searches, counts that use an index, and updates [source]
- The `winningPlan.queryPlan.inputStage.stage` is `DISTINCT_SCAN`, which indicates that the index was used. For more information on the explain plan output, see [Explain Results.](https://www.mongodb.com/docs/manual/reference/explain-results.md#std-label-explain-results) [source]
- [`nindexes`](https://www.mongodb.com/docs/manual/reference/command/collstats.md#mongodb-data-collStats.nindexes) includes indexes currently being built in its count. [source]
- - the index bounds specified in [`min()`](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) and [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) must both refer to the keys of the same index. [source]
- Unless the [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) query is an equality condition on the `_id` field `{ _id: <value> }`, you must explicitly specify the index with the [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) method to run [`min()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) [source]
- - Using the ordering of the `{ item: 1, type: 1 }` index, [`min()`](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) limits the query to the documents that are at or above the index key bound of `item` equal to `apple` and `type` equal to `jonagold`, as in the following: [source]
- - Using the ordering of the index `{ price: 1 }`, [`min()`](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) limits the query to the documents that are at or above the index key bound of `price` equal to `1.39` and [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) limits the query to the documents that are below the index key bound of `price` equal to `1.99`: [source]
- | Keyword | Description | | --- | --- | | `"textScore"` | Returns the score associated with the corresponding [`$text`](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#mongodb-query-op.-text) query for each matching document. The text score signifies how well the document matched the [search term or terms.](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#std-label-match-operation-stemmed-words) `{ $meta: "textScore" }` must be used in conjunction with a `$text` query. In earlier versions, if not used in conjunction with a `$text` query, returns a score [source]
- Some [Drivers](https://www.mongodb.com/docs/drivers/) provide access to the documents by using an index on the cursor (i.e. `cursor[index]`). This is a shortcut for first calling the [`toArray()`](https://www.mongodb.com/docs/manual/reference/method/cursor.toarray.md#mongodb-method-cursor.toArray) method and then using an index on the resulting array. [source]
- In some cases, the query planner uses a `DISTINCT_SCAN` index plan that returns one document per index key value. `DISTINCT_SCAN` executes faster than `IXSCAN` if there are multiple documents per key value. However, index scan parameters might affect the time comparison of `DISTINCT_SCAN` and `IXSCAN`. [source]
- The cursor.explain("executionStats") and the db.collection.explain("executionStats") methods provide statistics about the performance of a query. These statistics can be useful in measuring if and how a query uses an index. See db.collection.explain() for details. [source]
- A document that provides counters for each index type and the number of accesses on each index. Each index type under `indexStats.features` has a `count` field that counts the total number of indexes for that type, and an `accesses` field that counts the number of accesses on that index. [source]
- - Run the [`explain`](https://www.mongodb.com/docs/manual/reference/command/explain.md#mongodb-dbcommand-dbcmd.explain) command on a change stream cursor. [source]
- The total number of index items scanned during queries and query-plan evaluation. This counter is the same as [`totalKeysExamined`](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.executionStats.totalKeysExamined) in the output of [`explain()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) [source]
- The total number of documents scanned during queries and query-plan evaluation. This counter is the same as [`totalDocsExamined`](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.executionStats.totalDocsExamined) in the output of [`explain()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) [source]
- The number of queries that performed a collection scan that did not use a [tailable cursor.](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) [source]
- The number of queries that performed a collection scan on a [`profile`](https://www.mongodb.com/docs/manual/reference/system-collections.md#mongodb-data--database-.system.profile) collection that did not use a [tailable cursor.](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) [source]
- The number of queries that performed a collection scan on a [`profile`](https://www.mongodb.com/docs/manual/reference/system-collections.md#mongodb-data--database-.system.profile) collection that used a [tailable cursor.](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) [source]
- The total number of queries that performed a collection scan on a [`profile`](https://www.mongodb.com/docs/manual/reference/system-collections.md#mongodb-data--database-.system.profile) collection. This includes queries that used both tailable and non-tailable cursors. [source]
- | Parameter | Necessity | Type | Description | | --- | --- | --- | --- | | `verbose` | Optional | String | Determines the amount of information to include in the explain output. The possible verbosity modes are: `allPlansExecution`; `executionStats`; `queryPlanner` (*Default*) For backwards compatibility with earlier versions of `explain()`, MongoDB interprets `true` as `allPlansExecution` and `false` as `queryPlanner`. For more information on the modes, see [Verbosity Modes.](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#std-label-explain-cursor-method-verbosity) | [source]
- The [`explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) method returns a document with the query plan and, optionally, the execution statistics. [source]
- The behavior of [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) and the amount of information returned depend on the `verbosity` mode. [source]
- By default, [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) runs in `queryPlanner` verbosity mode. [source]
- [`db.collection.explain().find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) is similar to [`db.collection.find().explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) with the following key differences: [source]
- If you run `cursor.explain()` against a database that does not exist on a sharded cluster, the execution stage reaches the end-of-stream and the operation does not create the database. For more information on end-of-stream execution stats, see [`explain.executionStats.executionStages.isEOF`.](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.executionStats.executionStages.isEOF) [source]
- [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) operations can return information regarding: [source]
- The following example runs [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) in ["executionStats"](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#std-label-explain-method-executionStats) verbosity mode to return the query planning and execution information for the specified [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) operation: [source]
- [`db.collection.explain().find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) returns a cursor, which allows for the chaining of query modifiers. To see the list of query modifiers supported by [`db.collection.explain().find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) as well as cursor-related methods, run: [source]
- The following example runs [`db.collection.explain()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) in `"queryPlanner"` verbosity mode to return the query planning information for the specified [`count()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#mongodb-method-db.collection.count) operation: [source]
- The [`collStats`](https://www.mongodb.com/docs/manual/reference/command/collstats.md#mongodb-dbcommand-dbcmd.collStats) or [`db.collection.stats()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.stats.md#mongodb-method-db.collection.stats) from the shell that provides statistics that resemble [`dbStats`](https://www.mongodb.com/docs/manual/reference/command/dbstats.md#mongodb-dbcommand-dbcmd.dbStats) on the collection level, including a count of the objects in the collection, the size of the collection, the amount of disk space used by the collection, and information about [source]
- ```javascript { cursor: { id: Long('0'), ns: 'test.$cmd.aggregate', firstBatch: [ { type: 'InconsistentIndex', description: 'Found an index of a sharded collection that is inconsistent between different shards', details: { namespace: 'test.reviews', info: { missingFromShards: [], inconsistentProperties: [ { k: 'expireAfterSeconds', v: Long('600') }, { k: 'expireAfterSeconds', v: 3600 } ], indexName: 'reviewDt_1' } } }, { type: 'InconsistentIndex', description: 'Found an index of a sharded collection that is inconsistent between different shards', details: { namespace: 'test.reviews', info: { m [source]
- - The [cursor.explain()](https://www.mongodb.com/docs/manual/reference/method/cursor.explain/) command for [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) provides performance details for all queries. [source]
- Counts of the data access paths and index bounds that the winning plans use. A single winning plan can match multiple access path counters. [source]
- Counts the data access paths and index bounds that each winning plan uses. The access path counters are not mutually exclusive, so one query execution can increment several of them. [source]
- Each pattern counter name lists the stages of the winning plan in order, starting with the access path stage. For example, ixscanFetchSort counts winning plans that use an index scan, fetch the matching documents, and then sort them. [source]
- Scans that count index keys without returning documents. [source]
- Winning plans that don't use a collection scan, an index scan, a count scan, a distinct scan, or a geospatial access path. A plan that only performs a text search increments both textMatch and otherAccessPath. [source]
- Index scans where a field has multiple bounds, counted separately by the number of bounds. boundsUnionedSmall counts fields with 2 to 50 bounds, and boundsUnionedLarge counts fields with 51 or more bounds. [source]
- MongoDB cursors can return the same document more than once in some situations. As a cursor returns documents, other operations may interleave with the query. If one of these operations changes the indexed field on the index used by the query, then the cursor could return the same document more than once. [source]
- Queries that use [unique indexes](https://www.mongodb.com/docs/manual/core/index-unique.md#std-label-index-type-unique) can, in some cases, return duplicate values. If a cursor using a unique index interleaves with a delete and insert of documents sharing the same unique value, the cursor may return the same unique value twice from different documents. [source]
- | Subdocument | Description | | --- | --- | | `patterns` | Counts the overall shape of each winning plan. The patterns are mutually exclusive, so each query execution increments at most one pattern counter. | | `nodes` | Counts the types of plan stages that appear in each winning plan. The node counters are not mutually exclusive, so one query execution can increment several of them. | | `accessPaths` | Counts the data access paths and index bounds that each winning plan uses. The access path counters are not mutually exclusive, so one query execution can increment several of them. | [source]
- You must use the [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) command with the `cursor` option unless the command includes the `explain` option. [source]
- [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) supports the keyword `"indexKey"` to return index key metadata if an index is used. The use of [`{ $meta: "indexKey" }`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) is preferred over [`cursor.returnKey()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.returnkey.md#mongodb-method-cursor.returnKey) [source]
- If the query does not use an index to perform the read operation, the cursor returns empty documents. [source]
- A tailable cursor performs a collection scan over a [capped collection](https://www.mongodb.com/docs/manual/core/capped-collections.md#std-label-manual-capped-collection). It remains open even after reaching the end of the collection. Applications can continue to iterate the tailable cursor as new data is inserted into the collection. [source]
- Number of documents returned by the winning query plan. [`nReturned`](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.executionStats.nReturned) corresponds to the `n` field returned by `cursor.explain()` in earlier versions of MongoDB. [source]
- Number of index entries scanned. [`explain.executionStats.totalKeysExamined`](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.executionStats.totalKeysExamined) corresponds to the `nscanned` field returned by `cursor.explain()` in earlier versions of MongoDB. [source]
- If a document is examined multiple times during query execution, [`explain.executionStats.totalDocsExamined`](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.executionStats.totalDocsExamined) counts each examination. That is, [`explain.executionStats.totalDocsExamined`](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.executionStats.totalDocsExamined) is *not* a count of the total number of *unique* documents examined. [source]
- In previous versions of MongoDB, `cursor.explain()` returned the `clauses` array that detailed the indexes. [source]
- The cursor.explain() command for mongosh provides performance details for all queries. [source]
- In [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#std-program-mongosh), this command can also be run through the [`db.collection.explain()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) and [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) helper methods. [source]
- The following [`explain`](https://www.mongodb.com/docs/manual/reference/command/explain.md#mongodb-dbcommand-dbcmd.explain) command runs in `"queryPlanner"` verbosity mode to return the query planning information for a [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) command: [source]
- The following [`explain`](https://www.mongodb.com/docs/manual/reference/command/explain.md#mongodb-dbcommand-dbcmd.explain) operation runs in `"executionStats"` verbosity mode to return the query planning and execution information for a [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) command: [source]
- countDocuments() does not use metadata. It wraps aggregate([{$match: query}, {$group: {_id: null, n: {$sum: 1}}}]), giving an exact count even after unclean shutdown or with orphans, and its cost therefore follows the filter's index support. [source]
- | Column | Description | | --- | --- | | Collection Name | Name of the collection that the query shape targets. | | Average Execution Time | Average time spent running queries with the given query shape. | | Execution Count | Total number of times that queries with the given query shape ran. | | Docs Examined:Returned Ratio | Ratio of documents examined to documents returned by queries with the given query shape. | [source]
- If the batch size is too large, the cursor allocates more resources than it requires, which can negatively impact query performance. If the batch size is too small, the cursor requires more network round trips to retrieve the query results, which can negatively impact query performance. [source]
- Total time in microseconds spent running queries with the given query shape. If the query resulted in getMore commands, this metric includes the time spent processing the getMore requests. This metric does not include time spent waiting for the client. [source]
- Average time in microseconds spent running queries with the given query shape. If the query resulted in getMore commands, this metric includes the time spent processing the getMore requests. This metric does not include time spent waiting for the client. [source]
- The following table describes the query shape properties for count commands. [source]
- Each query shape property corresponds to a query option. For example, `key.queryShape.sort` corresponds to the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) specification for the query shape. [source]
- This loss of accuracy only applies to `count()` operations that do *not* include a query predicate. [source]
- If the collection has a `2dsphere` index instead, you can also specify the optional [`$minDistance`](https://www.mongodb.com/docs/manual/reference/operator/query/mindistance.md#mongodb-query-op.-minDistance) specification. For example, the following example returns the documents whose `location` is at least `0.0004` radians from the specified point, ordered from nearest to farthest: [source]
- For example, consider a `subway` collection with documents containing a `location` field, which specifies the coordinates of subway stations in a city. You often run queries with the [`$geoWithin`](https://www.mongodb.com/docs/manual/reference/operator/query/geowithin.md#mongodb-query-op.-geoWithin) operator to return a list of stations within a specific area. To improve performance for this query, you can create a geospatial index on the `location` field. After creating the index, you can query using the [`$near`](https://www.mongodb.com/docs/manual/reference/operator/query/near.md#mongodb-qu [source]
- The [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage filters the documents to only pass movies released before 1910 to the next stage. [source]
- - [`db.collection.countDocuments()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.countdocuments.md#mongodb-method-db.collection.countDocuments) which wraps the [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) aggregation stage with a [`$sum`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sum.md#mongodb-group-grp.-sum) expression. [source]
- You can use [`$currentOp`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-pipeline-pipe.-currentOp) to determine which collections are utilizing more connections in a cluster, enabling you to identify active client connections and their associated operations. [source]
- - Applies [`$mod`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/mod.md#mongodb-expression-exp.-mod) `2` to the `$clusterTime` variable's incrementing ordinal returned by [`$tsIncrement`.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsincrement.md#mongodb-expression-exp.-tsIncrement) [source]
- - Compares the returned value from [`$mod`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/mod.md#mongodb-expression-exp.-mod) to `0` using [`$eq`.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/eq.md#mongodb-expression-exp.-eq) [source]
- The following `cakeSalesCursor.next()` example output shows the `insert` details for the first document added to the `cakeSales` collection. Notice the incrementing ordinal `i` is `2` in the `clusterTime` field. [source]
- 3. The [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage uses `meta.type` as the group key to output one document per unique value. [source]
- [Collation](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation) allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. [source]
- MongoDB drivers and [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) associate all operations with a [server session](https://www.mongodb.com/docs/manual/reference/server-sessions.md), with the exception of unacknowledged write operations. For operations not explicitly associated with a session (i.e. using [`Mongo.startSession()`](https://www.mongodb.com/docs/manual/reference/method/mongo.startsession.md#mongodb-method-Mongo.startSession)), MongoDB drivers and `mongosh` create an implicit session and associate it with the operation. [source]
- The [com.mongodb.client.MongoCollection.find](https://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/client/MongoCollection.html#find--) method returns an instance of the [com.mongodb.client.FindIterable](https://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/client/FindIterable.html) interface. [source]
- [com.mongodb.reactivestreams.client.MongoCollection.find](http://mongodb.github.io/mongo-java-driver-reactivestreams/1.6/javadoc/com/mongodb/reactivestreams/client/MongoCollection.html#find\(\)) returns an instance of the [com.mongodb.reactivestreams.client.FindPublisher](http://mongodb.github.io/mongo-java-driver-reactivestreams/1.6/javadoc/com/mongodb/reactivestreams/client/FindPublisher.html) interface. [source]
- The [collection.find()](http://mongodb.github.io/mongo-scala-driver/2.9/scaladoc/org/mongodb/scala/MongoCollection.html#find[C]\(filter:org.mongodb.scala.bson.conversions.Bson\)\(implicite:org.mongodb.scala.bson.DefaultHelper.DefaultsTo[C,TResult],implicitct:scala.reflect.ClassTag[C]\):org.mongodb.scala.FindObservable[C]) method returns the find [Observable](http://mongodb.github.io/mongo-scala-driver/2.1/reference/observables/). [source]
- - [`$tsSecond`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tssecond.md#mongodb-expression-exp.-tsSecond) returns the seconds from `$clusterTime`, which is stored in `clusterTimeSeconds`. [source]
- The following aggregation operation uses the [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage to count the number of documents in the `movies` collection: [source]
- The following pipeline calculates the total runtime, average runtime, and movie count for each year before 1910: [source]
- The [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage groups the documents by year and calculates the total runtime, average runtime, and total count of the documents in each group. [source]
- The following aggregation operation specifies a group `_id` of `null`, calculating the total runtime, average runtime, and count of all documents in the collection. [source]
- mongod log messages, in the attr.command.cursor.comment field. [source]
- The `countDocuments()` method has the following form: [source]
- The `countDocuments()` method takes the following parameters: [source]
- | Parameter | Type | Description | | --- | --- | --- | | query | document | The query selection criteria. To count all documents, specify an empty document. See also [Query Restrictions.](https://www.mongodb.com/docs/manual/reference/method/db.collection.countdocuments.md#std-label-countDocuments-restrictions) | | options | document | Optional. Extra options that affects the count behavior. | [source]
- `countDocuments()` wraps the following aggregation operation and returns just the value of `n`: [source]
- `countDocuments()` returns `0` on an empty or non-existing collection or view. [source]
- `countDocuments()` can be used inside [distributed transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions) [source]
- If the client that issued `countDocuments()` disconnects before the operation completes, MongoDB marks `countDocuments()` for termination using [`killOp`.](https://www.mongodb.com/docs/manual/reference/command/killop.md#mongodb-dbcommand-dbcmd.killOp) [source]
- Counts documents in a collection or view. Returns a document with the count, `n`, and the command status, `ok`. [source]
- In [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#std-program-mongosh), this command can also be run through the [`count()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#mongodb-method-db.collection.count) helper method. [source]
- MongoDB validates option names for the [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) command. The command errors if you specify an unknown option name. [source]
- Starting in MongoDB 6.0, the `count` command is included in [Stable API](https://www.mongodb.com/docs/manual/reference/stable-api.md#std-label-stable-api) V1. To use the `count` command in the Stable API, you must connect your driver to a deployment running MongoDB 6.0 or later. [source]
- You can use the [`$count`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#mongodb-pipeline-pipe.-count) stage to count the documents. For example, the following operation counts the documents in a collection: [source]
- The [`$count`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#mongodb-pipeline-pipe.-count) stage is equivalent to the following [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) + [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) sequence: [source]
- [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#mongodb-pipeline-pipe.-collStats) to return an approximate count based on the collection's metadata. [source]
- After an unclean shutdown of a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) using the [Wired Tiger](https://www.mongodb.com/docs/manual/core/wiredtiger.md) storage engine, count statistics reported by [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) may be inaccurate. [source]
- This loss of accuracy only applies to [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) operations that do *not* include a query document. [source]
- The following operation counts all documents in the `orders` collection: [source]
- The following operation counts documents in the `orders` collection where the `ord_dt` field is greater than `Date('01/01/2012')`: [source]
- The following operation counts documents in the `orders` collection where the `ord_dt` field is greater than `Date('01/01/2012')`, skipping the first `10` matches: [source]
- Counts and returns the total number of items in an array. [source]
- { $sample: { size: <positive integer N> } } [source]
- [ { $sample: { size: 3 } } ] [source]
- const pipeline = [{ $sample: { size: 5 } }]; [source]
- const cursor = collection.aggregate(pipeline); [source]
- Specifies the order in which the query returns matching documents. You must apply [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) to the cursor before retrieving any documents from the database. [source]
- The [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method has the following parameter: [source]
- The sort document can specify [ascending or descending sort on existing fields](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-asc-desc) or [sort on text score metadata.](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-metadata) [source]
- The following command uses the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method to sort on the `borough` field: [source]
- The [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural) parameter returns items according to their [natural order](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-natural-order) within the database. This ordering is an internal implementation feature, and you should not rely on any particular ordering of the documents. [source]
- If reporting on a `getmore` operation before the `getmore` has accessed its cursor information, the [`cursor`](https://www.mongodb.com/docs/manual/reference/command/currentop.md#mongodb-data-currentOp.cursor) field is not available. [source]
- If the cursor is actively in use (i.e. [`op`](https://www.mongodb.com/docs/manual/reference/command/currentop.md#mongodb-data-currentOp.op) is `getmore` and the [`type`](https://www.mongodb.com/docs/manual/reference/command/currentop.md#mongodb-data-currentOp.type) is not `idleCursor`), then [`lastAccessDate`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-data--currentOp.cursor.lastAccessDate) reports either the time the previous `getmore` ended or the time the cursor was created if this is the first `getmore`. [source]
- The cumulative number of documents returned by the cursor. [source]
- The cumulative number of batches returned by the cursor. [source]
- For a change stream cursor, the operation time of the cursor's current position in the oplog. The value is the timestamp of the most recent oplog entry that the cursor read, including entries that don't produce a change event. The value can therefore be ahead of the most recent event that the cursor returned. [source]
- The value updates once per [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) command, so progress that a cursor makes during a `getMore` operation isn't visible until the operation returns. [source]
- The field appears only for change stream cursors. [source]
- For non-tailable cursors, the value is always false. [source]
- The `opid` of the operation using the cursor. [source]
- This page describes the `$count` aggregation pipeline stage. You can also use `$count` in these other contexts: [source]
- - [`$count (accumulator)`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#mongodb-group-grp.-count), which returns the number of documents in a group. [source]
- - [`$count (window function)`](https://www.mongodb.com/docs/manual/reference/mql/window-functions/count.md#mongodb-window-window.-count), which is used in the [`$setWindowFields`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setwindowfields.md#mongodb-pipeline-pipe.-setWindowFields) stage to return the number of documents in a particular window. [source]
- You can use `$count` for deployments hosted in the following environments: [source]
- The return type is represented by the smallest type that can store the final value of count: [`integer`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Int32) → [`long`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Int64) → [`double`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Double) [source]
- If the input dataset is empty, `$count` doesn't return a result. [source]
- 2. The `$count` stage returns a count of the remaining documents in the aggregation pipeline and assigns the value to a field called `perfect_score_count`. [source]
- The database profiler captures data information about read and write operations, cursor operations, and database commands. To configure the database profile and set the thresholds for capturing profile data, see the Database Profiler section. [source]
- "getMore" : Long("19234103609"), [source]
- The ID of the cursor accessed by a query and getmore operations. [source]
- The system.profile collection includes metrics for the getMore operation. In this example, getMore returns additional documents from the test.report collection. [source]
- "getMore" : Long("33629063128"), [source]
- | Field Name | Description | | --- | --- | | `latency` | The total latency, in microseconds. | | `ops` | The total number of operations performed on the collection since startup. | | `histogram` | An array of embedded documents, each representing a latency range. Each document covers twice the previous document's range. For lower values between 2048 microseconds and roughly 1 second, the histogram includes half-steps. This field only exists given the `latencyStats: { histograms: true }` option. Empty ranges with a zero `count` are omitted from the output. Each document has the following fields [source]
- The `count` field only exists in the output if you specify the `count` option. [source]
- The count is based on the collection's metadata, which provides a fast but sometimes inaccurate count for sharded clusters. [source]
- If you run `$collStats` with the `count: {}` option on a `matrices` collection: [source]
- For example, if you run `$collStats` on a sharded collection with the `count: {}` option on a collection named `matrices`: [source]
- ```csharp .Group( id: o => o.CustomerId, group: g => new { CustomerId = g.Key, FirstPurchaseDate = g.First().OrderDate, TotalValue = g.Sum(i => i.Value), TotalOrders = g.Count(), Orders = g.Select(i => new { i.OrderDate, i.Value }).ToList() } ) [source]
- ```cpp auto cursor = orders.aggregate(pipeline); ``` [source]
- ```php $cursor = $orders->aggregate($pipeline); ``` [source]
- ```go pipeline := mongo.Pipeline{ matchStage, sortStageOrderDate, groupStage, sortStageFirstPurchaseDate, setStage, unsetStage, } cursor, err := orders.Aggregate(ctx, pipeline) [source]
- ```rust let mut cursor = orders.aggregate(pipeline).await?; ``` [source]
- For example, running `getMore` on a cursor created by a [`find`](https://www.mongodb.com/docs/manual/reference/command/find.md#mongodb-dbcommand-dbcmd.find) operation on a sharded cluster returns a document similar to this output: [source]
- If [authentication](https://www.mongodb.com/docs/manual/core/authentication.md#std-label-authentication) is enabled, you can only run `getMore` against cursors you created. [source]
- Specifies the [collation](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation) for the cursor returned by the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find). To use, append to the [`db.collection.find()`.](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) [source]
- The [`cursor.collation()`](https://www.mongodb.com/docs/manual/reference/method/cursor.collation.md#mongodb-method-cursor.collation) accepts the following collation document: [source]
- The `$count` accumulator is available in these stages: [source]
- This page describes the [`$count`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#mongodb-group-grp.-count) aggregation accumulator. You can also use `$count` in these other contexts: [source]
- - [`$count (aggregation stage)`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#mongodb-pipeline-pipe.-count), which returns the number of input documents. [source]
- The `$count` accumulator does not accept any parameters. [source]
- The `$count` accumulator is functionally equivalent to using `{ $sum: 1 }` within the [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage. [source]
- This example uses [`$count`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#mongodb-group-grp.-count) in the [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage to count the number of movies in the `sample_mflix.movies` collection for each selected `genre`: [source]
- - `$count: {}` sets the `countNumberOfMoviesForGenre` field to the number of movies that share the same genre. [source]
- You can access the Performance Advisor with the [MongoDB MCP Server](https://www.mongodb.com/docs/mcp-server.md#std-label-what-is-mcp-server). This tool enables you to interact with your Atlas clusters in natural language from AI clients like Claude, Cursor, and Github Copilot. [source]
- The example in this section uses [`$tsIncrement`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsincrement.md#mongodb-expression-exp.-tsIncrement) in a [change stream cursor](https://www.mongodb.com/docs/manual/changestreams.md#std-label-changeStreams) to return every other change made to a collection in the same second of time. [source]
- - [`db.collection.watch()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#mongodb-method-db.collection.watch) method creates a [change stream cursor](https://www.mongodb.com/docs/manual/changestreams.md#std-label-changeStreams) for the `cakeSales` collection and stores the cursor in `cakeSalesCursor`. [source]
- If you modify this value, it does not change the iteration count for existing passwords. The [`scramIterationCount`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.scramIterationCount) value must be `5000` or greater. [source]
- If you modify this value, it does not change iteration count for existing passwords. The [`scramSHA256IterationCount`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.scramSHA256IterationCount) value must be `5000` or greater. [source]
- Sets the expiration threshold in milliseconds for idle cursors before MongoDB removes them; specifically, MongoDB removes cursors that have been idle for the specified [`cursorTimeoutMillis`.](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.cursorTimeoutMillis) [source]
- For example, the following sets the [`cursorTimeoutMillis`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.cursorTimeoutMillis) to `300000` milliseconds (5 minutes). [source]
- MongoDB cleans up [orphaned cursors](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-orphaned-cursor) after the `cursorTimeoutMillis` threshold only if they are not tied to sessions. [source]
- - Multiple arbiters prevent the reliable use of the majority write concern. MongoDB counts arbiters in calculating a membership majority, but arbiters do not store data. With the inclusion of multiple arbiters, it's possible for a majority write operation to return success before the write replicates to a majority of data bearing nodes. [source]
- Specifies the minimum effective timeout, in milliseconds, that the server enforces for streaming [`hello`](https://www.mongodb.com/docs/manual/reference/command/hello.md#mongodb-dbcommand-dbcmd.hello) commands sent by unauthenticated clients. If an unauthenticated client supplies a `maxAwaitTimeMS` value below this floor, the server either clamps the timeout up to this value or rejects the command, depending on [`abortStreamingHelloWithSmallTimeout`.](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.abortStreamingHelloWithSmallTimeout) [source]
- This parameter mitigates excessive CPU use from unauthenticated clients that send streaming `hello` commands with very small `maxAwaitTimeMS` values. [source]
- *Default*: `{ samplingRate: 0.01, maxTimeMS: 1000 }` [source]
- Sets the maximum oplog application batch size in bytes. [source]
- The `persistedChunkCacheUpdateMaxBatchSize` parameter specifies the maximum batch size used for updating the persisted chunk cache. [source]
- | Parameter | Type | Description | | --- | --- | --- | | `field` | string | The field for which to return distinct values. | | `query` | document | A query that specifies the documents from which to retrieve the distinct values. | | `options` | document | Optional. A document that specifies the options. See [Options.](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#std-label-distinct-method-options) | [source]
- The following diagram shows an example `distinct()` call. [source]
- For instance, if a field has as its value `[ 1, [1], 1 ]`, then [`db.collection.distinct()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#mongodb-method-db.collection.distinct) considers `1`, `[1]`, and `1` as separate values. [source]
- - For unsharded collections, you can use the [`db.collection.distinct()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#mongodb-method-db.collection.distinct) method/the [`distinct`](https://www.mongodb.com/docs/manual/reference/command/distinct.md#mongodb-dbcommand-dbcmd.distinct) command as well as the aggregation pipeline with the [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage. [source]
- If the client that issued `distinct()` disconnects before the operation completes, MongoDB marks `distinct()` for termination using [`killOp`.](https://www.mongodb.com/docs/manual/reference/command/killop.md#mongodb-dbcommand-dbcmd.killOp) [source]
- For information on `distinct()` and array fields, see the [Behavior](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#std-label-distinct-method-behavior-array) section. [source]
- The [`cursor.hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) method has the following parameter: [source]
- | Field Name | Type | Description | | --- | --- | --- | | `_id` | UUID | Sample ID for the query. | | `ns` | string | Namespace of the sampled collection. | | `collectionUuid` | UUID | ID of the sampled collection. | | `cmdName` | string | Name of the sampled command. Can be one of: `"find"`; `"aggregate"`; `"count"`; `"distinct"` | | `cmd.filter` | object | Filter the command ran with, if applicable. | | `cmd.collation` | object | Collation the command ran with, if applicable. | | `cmd.let` | object | Custom variables the command ran with, if applicable. | | `expireAt` | date | Date that the [source]
- db.collection.countDocuments() (mongosh method) [source]
- The query selection criteria. To count all documents, specify an empty document. See also Query Restrictions. [source]
- Optional. Extra options that affects the count behavior. [source]
- Optional. The maximum number of documents to count. [source]
- Optional. The maximum amount of time to allow the count to run. [source]
- countDocuments() can be used inside distributed transactions. [source]
- db.movies.countDocuments( { directors: "David Lynch" } ) [source]
- db.collection.estimatedDocumentCount() [source]
- collStats pipeline stage with the count option [source]
- db.collection.estimatedDocumentCount [source]
- The [`pretty()`](https://www.mongodb.com/docs/manual/reference/method/cursor.pretty.md#mongodb-method-cursor.pretty) method has the following prototype form: [source]
- By using [`cursor.pretty()`](https://www.mongodb.com/docs/manual/reference/method/cursor.pretty.md#mongodb-method-cursor.pretty) you can set the cursor to return data in a format that is easier to read: [source]
- Specifies the maximum time for the server to wait for new documents that match a [tailable cursor](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) query on a [capped collection](https://www.mongodb.com/docs/manual/core/capped-collections.md#std-label-manual-capped-collection). For more information on iterating a cursor returned by a query, see: [Iterate a Cursor in `mongosh`.](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#std-label-read-operations-cursors) [source]
- The [`maxAwaitTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxawaittimems.md#mongodb-method-cursor.maxAwaitTimeMS) method has the following prototype form: [source]
- The [`maxAwaitTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxawaittimems.md#mongodb-method-cursor.maxAwaitTimeMS) method has the following parameter: [source]
- The highlighted line creates a [tailable cursor](https://www.mongodb.com/docs/manual/core/tailable-cursors.md#std-label-tailable-cursors-landing-page) on the `sales` collection. The [`maxAwaitTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxawaittimems.md#mongodb-method-cursor.maxAwaitTimeMS) sets a one second maximum wait time for the next cursor update. [source]
- The [`min()`](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) method has the following parameter: [source]
- The bound specified by [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) must be greater than the bound specified by [`min()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) [source]
- If any of the previous conditions are false, [`$sample`:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) [source]
- This tutorial demonstrates how to access documents in a [cursor.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-cursor) [source]
- - Save a cursor as a variable using the `let` keyword. [source]
- - Use the [`next()`](https://www.mongodb.com/docs/manual/reference/method/cursor.next.md#mongodb-method-cursor.next), [`hasNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hasnext.md#mongodb-method-cursor.hasNext), and [`forEach()`](https://www.mongodb.com/docs/manual/reference/method/cursor.foreach.md#mongodb-method-cursor.forEach) methods to access documents in a cursor. [source]
- - Return and access the cursor documents as an array with the [`toArray()`](https://www.mongodb.com/docs/manual/reference/method/cursor.toarray.md#mongodb-method-cursor.toArray) method. [source]
- A cursor returns documents in batches. By default, mongosh displays 20 documents per cursor iteration. You can use [config.set("displayBatchSize")](https://www.mongodb.com/docs/mongodb-shell/reference/configure-shell-settings-api.md#std-label-mongosh-configure-api-params) to change it, if this is too much or too little for your needs. [source]
- You can call the cursor variable in the shell to print matching documents. [source]
- You can also use the cursor method [`next()`](https://www.mongodb.com/docs/manual/reference/method/cursor.next.md#mongodb-method-cursor.next) to access the documents. [`next()`](https://www.mongodb.com/docs/manual/reference/method/cursor.next.md#mongodb-method-cursor.next) returns the document the cursor currently points and then moves the cursor forward to the next document. [source]
- The cursor method [`hasNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hasnext.md#mongodb-method-cursor.hasNext) returns `true` or `false` to indicate if there are more documents to be returned from the cursor. [source]
- You can use the [`hasNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hasnext.md#mongodb-method-cursor.hasNext) and [`next()`](https://www.mongodb.com/docs/manual/reference/method/cursor.next.md#mongodb-method-cursor.next) methods to print all remaining documents from the cursor using the `printjson()` helper. [source]
- Similarly, you can use the cursor method [`forEach()`](https://www.mongodb.com/docs/manual/reference/method/cursor.foreach.md#mongodb-method-cursor.forEach) to apply a helper, such as `printjson()`, to each document in the cursor. [source]
- Starting in [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) 2.1.0, you can also use `for-of` loops to iterate the cursor. The following example returns the same results as the previous example. [source]
- See [JavaScript cursor methods](https://www.mongodb.com/docs/manual/reference/method.md#std-label-js-query-cursor-methods) and your [driver](https://www.mongodb.com/docs/drivers/) documentation for more information on cursor methods. [source]
- In [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh), use the [`toArray()`](https://www.mongodb.com/docs/manual/reference/method/cursor.toarray.md#mongodb-method-cursor.toArray) method to iterate the cursor and return the documents in an array. [source]
- The [`toArray()`](https://www.mongodb.com/docs/manual/reference/method/cursor.toarray.md#mongodb-method-cursor.toArray) method loads all documents returned by the cursor into RAM and exhausts the cursor. [source]
- [`cursor.hasNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hasnext.md#mongodb-method-cursor.hasNext) returns `true` if the cursor returned by the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) query can iterate further to return more documents. If the client-side cursor batch is empty and the server has more data, `hasNext()` fetches the next batch from the server. [source]
- In mongosh, this command can also be run through the db.collection.distinct() helper method. [source]
- For the equivalent mongosh method, see db.collection.distinct(). For driver-specific wrapper methods, see the driver documentation. [source]
- For unsharded collections, you can use the db.collection.distinct() method/the distinct command as well as the aggregation pipeline with the $group stage. [source]
- - The [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage selects a subset of the available fields, including `numComments`, which is the count of comments for each movie. [source]
- cursor.disableBlockWarnings [source]
- The following [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) example uses [`showRecordId()`](https://www.mongodb.com/docs/manual/reference/method/cursor.showrecordid.md#mongodb-method-cursor.showRecordId) to append the `$recordId` to the `pizza` document fields in the output: [source]
- Append [`readPref()`](https://www.mongodb.com/docs/manual/reference/method/cursor.readpref.md#mongodb-method-cursor.readPref) to a cursor to control how the client routes the query to members of the replica set. [source]
- You must apply [`readPref()`](https://www.mongodb.com/docs/manual/reference/method/cursor.readpref.md#mongodb-method-cursor.readPref) to the cursor before retrieving any documents from the database. [source]
- In the aggregation pipeline, [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) selects the documents where either the `runtime` is greater than `1000` or the `year` is earlier than `1910`. These documents are then sent to the [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) to perform a count. [source]
- - For more information on sorting query results, see [`sort()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) [source]
- The next document in the cursor returned by the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method. See [`cursor.hasNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hasnext.md#mongodb-method-cursor.hasNext) related functionality. [source]
- - It can be difficult to predict the complexity of the query or pipeline returned by the Compass AI. You may need to adjust the MAX TIME MS query bar option to either allow longer query processing time or prevent long-running queries. For details, see [Adjust Maximum Time for Query Operations.](https://www.mongodb.com/docs/compass/query/maxtimems.md#std-label-compass-query-bar-max-time-ms) [source]
- Type a natural language prompt for your collection into the query bar. Aggregation pipeline prompts usually have an aggregation verb such as count, average, or sum with logical conditions. For example: `How many movies have more than 3 writers in the writers array?` [source]
- Returns a [Change Stream](https://www.mongodb.com/docs/manual/changestreams.md#std-label-changeStreams) cursor on a collection, a database, or an entire cluster. Must be used as the first stage in an aggregation pipeline. [source]
- For details on how MongoDB stops queries that exceed a specified timeout, see [cursor.maxTimeMS Behaviors.](https://www.mongodb.com/docs/manual/reference/method/cursor.maxtimems.md#std-label-cursor-maxtimems-behaviors) [source]
- - Specify the [`maxTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxtimems.md#mongodb-method-cursor.maxTimeMS) option for a query. The `maxTimeMS` option lets you specify a query timeout at the operation level, meaning you can specify different time limits for different queries. [source]
- A document that reports statistics on collection usage via collection counts. [source]
- Count of **all** incoming connections created to the server. This number includes connections that have since closed. [source]
- Windows differentiates "hard" page faults involving disk I/O from "soft" page faults that only require moving pages in memory. MongoDB counts both hard and soft page faults in this statistic. [source]
- The number of registered encrypted collections using each query type. A collection counts toward every applicable metric, including `unindexed` if it has encrypted fields with no query types enabled. [source]
- Counts of Queryable Encryption operations. [source]
- Counts how many times this lock runs in write mode, blocking other threads until the write finishes. [source]
- The number of cursors that were closed during the last [`config.system.sessions`](https://www.mongodb.com/docs/manual/reference/config-database.md#mongodb-data-config.system.sessions) collection refresh. [source]
- The number of change stream cursors with the [showExpandedEvents](https://www.mongodb.com/docs/manual/reference/change-events.md#std-label-change-streams-expanded-events) option set to `true`. [source]
- - Open a change stream cursor. [source]
- Each histogram groups command values into buckets. Each bucket reports the `count` of commands with a value in that bucket's range, and `totalCount` reports the total number of commands counted across all buckets. [source]
- A histogram of the `batchSize` cursor option values set on change stream [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) and [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) commands, with bucket boundaries at 1, 10, 100, 1000, and 10000. [source]
- A histogram of the `maxTimeMS` cursor option values set on change stream [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) and [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) commands, with bucket boundaries at 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, and 1000000. [source]
- The histogram is only incremented for commands that set a `maxTimeMS` value. [source]
- The throughput counters update once per [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) or [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) command run against a change stream cursor. The `open` values report the number of cursors open at the time [`serverStatus`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-dbcommand-dbcmd.serverStatus) runs. The `totalOpened` value is cumulative, and the `lifespan` values cover cursors that have clo [source]
- The cumulative number of batches returned by all change stream cursors. [source]
- The cumulative amount, in bytes, of oplog scanned by all change stream cursors. [source]
- The cumulative amount, in bytes, returned by all change stream cursors. [source]
- The cumulative number of oplog entries scanned by all change stream cursors. [source]
- The cumulative number of change stream events returned by all change stream cursors. [source]
- The number of open change stream cursors that are pinned. A pinned cursor is one that an operation is actively using. [source]
- A document that reports the number of errors encountered by change stream cursors, categorized by whether the errors are retriable. [source]
- The number of times a replica set state change, such as a primary stepping down, interrupted a change stream cursor. [source]
- A document that reports [write concern](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-write-concern) operation counts with a `w` argument greater than `1`. [source]
- Total number of operations that timed out due to the operation-level timeout, [`cursor.maxTimeMS()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.maxtimems.md#mongodb-method-cursor.maxTimeMS) [source]
- Starting in MongoDB 8.0, secondaries use separate buffers to write and apply oplog entries. For the current number of operations in the oplog buffers, see the [`apply.count`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.repl.buffer.apply.count) or [`write.count`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.repl.buffer.write.count) status metrics. [source]
- This metric does not include [oplog](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-oplog) reads used by backup cursors, change streams, or [`mongodump`.](https://www.mongodb.com/docs/database-tools/mongodump.md#std-program-mongodump) [source]
- [`metrics.repl.network.getmores.num`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.repl.network.getmores.num) reports the total number of `getmore` operations, which are operations that request an additional set of operations from the replication sync source. [source]
- [`metrics.repl.network.getmores.totalMillis`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.repl.network.getmores.totalMillis) reports the total amount of time required to collect data from `getmore` operations. [source]
- This number can be quite large, as MongoDB will wait for more data even if the `getmore` operation does not initial return data. [source]
- - The `getmore` times out waiting for more data, or [source]
- A document that reports the number of [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) commands to fetch the [oplog](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-oplog) that a node processed as a sync source. [source]
- The number of [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) commands to fetch the [oplog](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-oplog) that a node processed as a sync source. [source]
- The time, in milliseconds, that a node spent processing the [`getMore`](https://www.mongodb.com/docs/manual/reference/command/getmore.md#mongodb-dbcommand-dbcmd.getMore) commands counted in [`metrics.repl.network.oplogGetMoresProcessed.num`.](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.repl.network.oplogGetMoresProcessed.num) [source]
- The number of cursors with a lifespan >= 10 minutes. [source]
- The number of cursors with a lifespan >= 1 minute to \< 10 minutes. [source]
- The number of cursors with a lifespan >= 5 seconds to \< 15 seconds. [source]
- The number of cursors with a lifespan >= 30 seconds to \< 1 minute. [source]
- The number of cursors with a lifespan \< 1 second. [source]
- The number of cursors with a lifespan >= 15 seconds to \< 30 seconds. [source]
- The number of cursors with a lifespan >= 1 second to \< 5 seconds. [source]
- The number of open cursors with the option [`DBQuery.Option.noTimeout`](https://www.mongodb.com/docs/manual/reference/method/cursor.addoption.md#mongodb-data-DBQuery.Option.noTimeout) set to prevent timeout after a period of inactivity. [source]
- The number of "pinned" open cursors. [source]
- More specifically, the [`opWriteConcernCounters`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.opWriteConcernCounters) reports on the [w: \<value>](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-wc-w) specified by the write operations. The journal flag option (`j`) and the timeout option (`wtimeout`) of the write concerns does not affect the count. The count is incremented even if the operation times out. [source]
- | Specified `w` | Description | | --- | --- | | `"wmajority"` | Number of insert operations that specified [`w: "majority"`.](https://www.mongodb.com/docs/manual/reference/write-concern.md#mongodb-writeconcern-writeconcern.-majority-) | | `"wnum"` | Number of insert operations that specified [`w: <num>`](https://www.mongodb.com/docs/manual/reference/write-concern.md#mongodb-writeconcern-writeconcern.-number-). The counts are grouped by the specific``<num>``. | | `"wtag"` | Number of insert operations that specified [`w: <tag>`](https://www.mongodb.com/docs/manual/reference/write-concern.md#mon [source]
- | Specified `w` | Description | | --- | --- | | `"wmajority"` | Number of update operations that specified [`w: "majority"`.](https://www.mongodb.com/docs/manual/reference/write-concern.md#mongodb-writeconcern-writeconcern.-majority-) | | `"wnum"` | Number of update operations that specified [`w: <num>`](https://www.mongodb.com/docs/manual/reference/write-concern.md#mongodb-writeconcern-writeconcern.-number-). The counts are grouped by the specific `<num>`. | | `"wtag"` | Number of update operations that specified [`w: <tag>`](https://www.mongodb.com/docs/manual/reference/write-concern.md#mong [source]
- | Specified `w` | Description | | --- | --- | | `"wmajority"` | Number of delete operations that specified [`w: "majority"`.](https://www.mongodb.com/docs/manual/reference/write-concern.md#mongodb-writeconcern-writeconcern.-majority-) | | `"wnum"` | Number of delete operations that specified [`w: <num>`](https://www.mongodb.com/docs/manual/reference/write-concern.md#mongodb-writeconcern-writeconcern.-number-). The counts are grouped by the specific `<num>`. | | `"wtag"` | Number of delete operations that specified [`w: <tag>`](https://www.mongodb.com/docs/manual/reference/write-concern.md#mong [source]
- [`opcounters.command`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.opcounters.command) counts all [commands](https://www.mongodb.com/docs/manual/reference/command.md#std-label-database-commands) **except** the following: [source]
- The cumulative count of operations that are heuristically deprioritized during the server's lifetime. [source]
- Document with configuration counts and usage for query settings. [source]
- The cumulative, always-increasing count of documents that MongoDB clones on the primary node of the recipient shard. [source]
- The cumulative, always-increasing count of documents that MongoDB clones on the primary node of the donor shard. [source]
- Cumulative, always-increasing count of chunks this member, acting as the primary of the recipient shard, has started to receive (whether the move has succeeded or not). [source]
- The cumulative, always-increasing count of documents that MongoDB deletes on the primary node of the donor shard during chunk migration. [source]
- The cumulative, always-increasing count of chunk migrations that MongoDB aborts on the primary node of the donor shard due to lock acquisition timeouts. [source]
- A document with statistics about the critical sections for databases, including counts of how many operations hold the critical section, how many are waiting, and how long they have waited. [source]
- A document with statistics about the critical sections for collections, including counts of how many operations hold the critical section, how many are waiting, and how long they have waited. [source]
- A document with statistics about [`checkMetadataConsistency`](https://www.mongodb.com/docs/manual/reference/command/checkmetadataconsistency.md#mongodb-dbcommand-dbcmd.checkMetadataConsistency) command executions, including check counts and time spent holding DDL locks. [source]
- A document that returns statistics on WiredTiger cursor. [source]
- Additionally, if you run the `killCursors` command within a transaction, the server immediately stops the specified cursors. It does **not** wait for the transaction to commit. [source]
- - Other non-CRUD and non-informational operations, such as [`createUser`](https://www.mongodb.com/docs/manual/reference/command/createuser.md#mongodb-dbcommand-dbcmd.createUser), [`getParameter`](https://www.mongodb.com/docs/manual/reference/command/getparameter.md#mongodb-dbcommand-dbcmd.getParameter), [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count), etc. and their helpers. [source]
- Sessions that receive no read or write operations for 30 minutes *or* that are not refreshed using [`refreshSessions`](https://www.mongodb.com/docs/manual/reference/command/refreshsessions.md#mongodb-dbcommand-dbcmd.refreshSessions) within 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 with [`noCursorTimeout()`](https://www.mongodb.com/docs/manual/reference/method/cursor.nocursortimeout.md#mongodb-method-cursor.noCursorTime [source]
- 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 [`Mongo.startSession()`](https://www.mongodb.com/docs/manual/reference/method/mongo.startsession.md#mongodb-method-Mongo.startSession) and periodically refresh the session using the [`refreshSessions`](https://www.mongodb.com/docs/manual/reference/command/refreshsessions.md#mongodb-dbcommand-dbcmd.refreshSessions) command. For example: [source]
- In the example operation, the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method is associated with an explicit session. The cursor is configured with [`noCursorTimeout()`](https://www.mongodb.com/docs/manual/reference/method/cursor.nocursortimeout.md#mongodb-method-cursor.noCursorTimeout) to prevent the server from closing the cursor if idle. The `while` loop includes a block that uses [`refreshSessions`](https://www.mongodb.com/docs/manual/reference/command/refreshsessions.md#mongodb-dbcommand-dbcmd.re [source]
- Returns the count of all documents in a collection or view. [source]
- db.collection.estimatedDocumentCount() does not take a query filter and instead uses metadata to return the count for a collection. [source]
- The document count is calculated by executing the aggregation pipeline in the view definition. [source]
- There is no fast estimated document count. [source]
- On a sharded cluster, the resulting count will not correctly filter out orphaned documents. [source]
- After an unclean shutdown, the count may be incorrect. [source]
- validate updates the count statistic in the collStats output with the latest value. [source]
- If the client that issued db.collection.estimatedDocumentCount() disconnects before the operation completes, MongoDB marks db.collection.estimatedDocumentCount() for termination using killOp. [source]
- db.movies.estimatedDocumentCount({}) [source]
- Iterates the cursor to apply a JavaScript `function` to each document from the cursor. [source]
- | Field | Type | Description | | --- | --- | --- | | `function` | JavaScript code | Function to apply to each document returned from the cursor. The function signature includes one field that stores the current document that is read from the cursor. | [source]
- For a method that has similar functionality, see [`cursor.map()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.map.md#mongodb-method-cursor.map) [source]
- | **Example** | **Metrics** | **Metadata** | | --- | --- | --- | | Stock data | Stock price | Stock ticker, exchange | | Weather data | Temperature | Sensor identifier, location | | Website visitors | View count | URL | [source]
- [`mongostat`](https://www.mongodb.com/docs/database-tools/mongostat.md#mongodb-binary-bin.mongostat) captures and returns the counts of database operations by type (e.g. insert, query, update, delete, etc.). These counts report on the load distribution on the server. [source]
- Each write of an encrypted field value also writes two metadata documents per tag, one to the ESC and one to the ECOC, so write throughput scales with the tag count in the same way as storage. [source]
- 1. Calculate the worst-case tag count for each field and query type. [source]
- Using the tag count from the previous step, calculate the storage a single document requires for the field, in bytes. Use the following formulas, where `v` is the average byte length of the field's unencrypted values. [source]
- Selects documents in a collection or view and returns a [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) to the selected documents. [source]
- Executing `find()` in [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) automatically iterates the cursor to display up to the first 20 documents. Type `it` to continue iteration. [source]
- The `find()` method returns a [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) to the results. [source]
- In [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh), if the returned cursor is not assigned to a variable using the `var` keyword, the cursor is automatically iterated to access up to the first 20 documents that match the query. You can update the `displayBatchSize` variable to change the number of automatically iterated documents. [source]
- The following example sets the batch size to 3. Future `find()` operations will only return 3 documents per cursor iteration. [source]
- The following example uses the variable `myCursor` to iterate over the cursor and print the matching documents: [source]
- [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) and the [drivers](https://www.mongodb.com/docs/drivers/) provide several cursor methods that call on the *cursor* returned by `find()` to modify its behavior. [source]
- The [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method orders the documents in the result set. The following operation returns documents in the [bios collection](https://www.mongodb.com/docs/manual/reference/bios-example-collection.md) sorted in ascending order by the `name` field: [source]
- [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) corresponds to the `ORDER BY` statement in SQL. [source]
- [`cursor.isClosed()`](https://www.mongodb.com/docs/manual/reference/method/cursor.isclosed.md#mongodb-method-cursor.isClosed) returns `true` if the server has closed the cursor. [source]
- A closed cursor may still have documents remaining in the last received batch. Use [`cursor.isExhausted()`](https://www.mongodb.com/docs/manual/reference/method/cursor.isexhausted.md#mongodb-method-cursor.isExhausted) or [`cursor.hasNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hasnext.md#mongodb-method-cursor.hasNext) to check if the cursor is fully exhausted. [source]
- Adjust `batchSize` to a value appropriate to your database, load, and application needs. [source]
- The [`batchSize()`](https://www.mongodb.com/docs/manual/reference/method/cursor.batchsize.md#mongodb-method-cursor.batchSize) method takes the following field: [source]
- The following example sets `batchSize` for the results of a query (specifically, [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find)) to `10`: [source]
- Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group. [source]
- The documents are sorted by `count` in descending order. [source]
- The following operation [`unwinds`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind.md#mongodb-pipeline-pipe.-unwind) the `tags` array and uses the [`$sortByCount`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortbycount.md#mongodb-pipeline-pipe.-sortByCount) stage to count the number of documents associated with each tag: [source]
- For more information on how to access data from a cursor, see [Access Data From a Cursor.](https://www.mongodb.com/docs/drivers/csharp/sync/current/crud/query-documents/cursor/) [source]
- For more information on how to access data from a cursor, see [Access Data From a Cursor.](https://www.mongodb.com/docs/drivers/java/sync/current/crud/query-documents/cursor/) [source]
- This example groups all documents by the date of the measurement, then calculates the average of all temperature measurements that day and returns a [cursor:](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) [source]
- For more information on how to access data from a cursor, see [Access Data From a Cursor.](https://www.mongodb.com/docs/drivers/node/current/crud/query/cursor/) [source]
- The example returns a [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors). You can use the cursor to iterate through the resulting documents: [source]
- For more information on how to access data from a cursor, see [Access Data From a Cursor.](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/query/cursors/) [source]
- - Returns a [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) that can be used to iterate through the resulting documents [source]
- [`comment()`](https://www.mongodb.com/docs/manual/reference/method/cursor.comment.md#mongodb-method-cursor.comment) associates a comment string with the find operation. This can make it easier to track a particular query in the following diagnostic outputs: [source]
- The following operation groups the documents into buckets according to the `year_born` field and filters based on the count of documents in the buckets: [source]
- | Field | Description | | --- | --- | | `_id` | Inclusive lower bound of the bucket. | | `count` | Count of documents in the bucket. | | `artwork` | Array of documents containing information on each artwork in the bucket. | | `averagePrice` | Employs the [`$avg`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/avg.md#mongodb-group-grp.-avg) operator to display the average price of all artwork in the bucket. | [source]
- | Field | Description | | --- | --- | | `count` | Count of documents in the bucket. | | `artwork` | Array of documents containing information on each artwork in the bucket. | [source]
- - [mongod log messages](https://www.mongodb.com/docs/manual/reference/log-messages.md#std-label-log-messages-ref), in the `attr.command.cursor.comment` field. [source]
- $queryStats collects and reports metrics for aggregate(), find(), distinct(), count(), update(), insert(), deleteOne(), and deleteMany() queries. $queryStats does not collect information for queries that use Queryable Encryption. [source]
- Internal getMore operations increment the execCount metric. [source]
- noCursorTimeout option associated with the key [source]
- Metrics related to the cursor and batching protocol [source]
- Counts of the plan shapes that MongoDB selected for queries with the given key. For details, see Plan Shape Counters. [source]
- Counts of the overall shapes of the winning plans. Each winning plan matches at most one pattern. [source]
- Counts of the types of plan stages that appear in the winning plans. A single winning plan can match multiple node counters. [source]
- Describes the total time spent running queries with the given key. If the query resulted in getMores, totalExecMicros includes the time spent processing the getMore requests. totalExecMicros does not include time spent waiting for the client. [source]
- Number of times a query operation calls checkForInterrupt per second. This metric becomes aggregated if you run the query in multiple batches using getMores. [source]
- Counts the overall shape of each winning plan. The patterns are mutually exclusive, so each query execution increments at most one pattern counter. [source]
- Counts the types of plan stages that appear in each winning plan. The node counters are not mutually exclusive, so one query execution can increment several of them. [source]
- Skip stages, counted separately by skip value. skipSmall counts skips of 100 or less, skipMedium counts skips from 101 to 10,000, and skipLarge counts skips greater than 10,000. [source]
- The fields in key.queryShape vary based on the command that resulted in the query stats entry. $queryStats creates query stats entries for aggregate, find, distinct, count, update, insert, and delete commands. [source]
- cursor: { batchSize: '?number' } [source]
- - A [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) for the documents produced by the final stage of the aggregation pipeline. [source]
- - If the pipeline includes the [`$out`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/out.md#mongodb-pipeline-pipe.-out) or [`$merge`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge) operators, the query returns an empty cursor. [source]
- Cursors returned from aggregation only supports cursor methods that operate on evaluated cursors (i.e. cursors whose first batch has been retrieved), such as the following methods: [source]
- [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) iterates the returned cursor automatically to print the results. See [Iterate a Cursor in mongosh](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md) for handling cursors manually in [`mongosh`.](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) [source]
- For example, the following aggregation operation specifies the *initial* batch size of `0` for the cursor: [source]
- The [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) method has the following parameter: [source]
- [`$listLocalSessions`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listlocalsessions.md#mongodb-pipeline-pipe.-listLocalSessions) returns a cursor with one document per session cached in memory. Each document has the following prototype: [source]
- Executes a query and returns the first batch of results and the cursor id, from which the client can construct a cursor. [source]
- | Granularity | Results | Notes | | --- | --- | --- | | No granularity | **{ "_id" : { "min" : 0, "max" : 20 }, "count" : 20 }****{ "_id" : { "min" : 20, "max" : 40 }, "count" : 20 }****{ "_id" : { "min" : 40, "max" : 60 }, "count" : 20 }****{ "_id" : { "min" : 60, "max" : 80 }, "count" : 20 }****{ "_id" : { "min" : 80, "max" : 99 }, "count" : 20 }** | | | R20 | **{ "_id" : { "min" : 0, "max" : 20 }, "count" : 20 }****{ "_id" : { "min" : 20, "max" : 40 }, "count" : 20 }****{ "_id" : { "min" : 40, "max" : 63 }, "count" : 23 }****{ "_id" : { "min" : 63, "max" : 90 }, "count" : 27 }****{ "_id" : [source]
- If the argument for [`$binarySize`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/binarysize.md#mongodb-expression-exp.-binarySize) is a string, the operator counts the number of UTF-8 encoded bytes in a string where each character may use between one and four bytes. [source]
- Consider the following example that applies [`toArray()`](https://www.mongodb.com/docs/manual/reference/method/cursor.toarray.md#mongodb-method-cursor.toArray) to the cursor returned from the [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method: [source]
- The variable `allProductsArray` holds the array of documents returned by [`toArray()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.toarray.md#mongodb-method-cursor.toArray) [source]
- The [`$accumulator`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#mongodb-group-grp.-accumulator) defines an initial state where `count` and `sum` are both set to `0`. For each document that the [`$accumulator`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#mongodb-group-grp.-accumulator) processes, it updates the state by: [source]
- Once all documents have been processed, the [finalize](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#std-label-accumulator-finalize) function divides the `sum` of the copies by the `count` of documents to obtain the average. This removes the need to keep a running computed average, since the [finalize](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#std-label-accumulator-finalize) function receives the cumulative `sum` and `count` of all documents. [source]
- - To indicate a cursor with the default batch size, specify `cursor: {}`. [source]
- - To indicate a cursor with a non-default batch size, use `cursor: { batchSize: <num> }`. [source]
- The following example aggregates the `movies` collection to calculate the count of each distinct genre: [source]
- - Use [`cursor.maxTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxtimems.md#mongodb-method-cursor.maxTimeMS) for reads and [`wtimeout`](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-wc-wtimeout) for writes if you need to cap execution time for database operations. [source]
- Instructs the server to close a [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) and free associated server resources. The server will automatically close cursors that have no remaining results, as well as cursors that have been idle for a period of time and lack the [`cursor.noCursorTimeout()`](https://www.mongodb.com/docs/manual/reference/method/cursor.nocursortimeout.md#mongodb-method-cursor.noCursorTimeout) option. [source]
- The [`close()`](https://www.mongodb.com/docs/manual/reference/method/cursor.close.md#mongodb-method-cursor.close) method has the following prototype form: [source]
- The [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage groups by `year` and counts films into a new `movieCount` field. [source]
- Similarly, run the following aggregation pipeline against the `comments` collection to merge the comment counts into the `yearlyStats` collection. [source]
- The [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage groups by the year extracted from the comment `date` and counts comments into a new `commentCount` field. [source]
- A collection `monthlyCommentTotals` tracks the running count of comments for each month. [source]
- Each day, new comments arrive in the `sample_mflix.comments` collection. The following aggregation pipeline updates the monthly total with that day's comment count: [source]
- The [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage groups the matching comments by year-month and counts them. [source]
- The `$merge` stage writes the documents to the `monthlyCommentTotals` collection. If the stage finds an existing document in the collection that [matches on](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#std-label-merge-on) the `_id` field, the stage uses a pipeline to add the day's `count` to the existing monthly total. [source]
- - This pipeline can directly access the `count` field in the existing document in the collection; i.e. `$count`. [source]
- [`$listSessions`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listsessions.md#mongodb-pipeline-pipe.-listSessions) returns a cursor with one document per session. Each document has the following prototype: [source]
- Available tabs: other tabs: query, getmore, update --> [source]
- The database profiler captures data information about read and write operations, cursor operations, and database commands. To configure the database profile and set the thresholds for capturing profile data, see the [Database Profiler](https://www.mongodb.com/docs/manual/tutorial/manage-the-database-profiler.md#std-label-database-profiler) section. [source]
- The [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) that [`returnKey()`](https://www.mongodb.com/docs/manual/reference/method/cursor.returnkey.md#mongodb-method-cursor.returnKey) is attached to with a modified result set. This allows for additional cursor modifiers to be chained. [source]
- `~cursor.tailable()` has the following parameter: [source]
- The [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) that `~cursor.tailable()` is attached to. [source]
- [`cursor.objsLeftInBatch()`](https://www.mongodb.com/docs/manual/reference/method/cursor.objsleftinbatch.md#mongodb-method-cursor.objsLeftInBatch) returns the number of documents remaining in the current batch. [source]
- The following example silences warnings on a tailable cursor that is stored in a variable called `myTailableCursor`: [source]
- The following pipeline unwinds the `genres` array and groups the resulting documents by genre to count the number of movies in each genre: [source]
- | Field | Type | Description | | --- | --- | --- | | `planCacheListFilters` | string | The name of the collection. | | `comment` | any | Optional. A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations: [mongod log messages](https://www.mongodb.com/docs/manual/reference/log-messages.md#std-label-log-messages-ref), in the `attr.command.cursor.comment` field.; [Database profiler](https://www.mongodb.com/docs/manual/reference/database-profiler.md#std-label-profiler) output, in the [`command.comment`](https://w [source]
- `$dateDiff` counts the unit boundaries crossed between `startDate` and `endDate`. It does not measure elapsed duration. For example, `$dateDiff` reports a difference of one `year` between December 31, 2022 and January 1, 2023. A year boundary was crossed, even though a few hours passed between the two dates. See [Year Boundary Crossing](https://www.mongodb.com/docs/manual/reference/operator/aggregation/datediff.md#std-label-dateDiff-year-boundary-example) for a full example. [source]
- The start of the `week` is `Sunday` unless modified by the `startOfWeek` parameter. `$dateDiff` counts any week that begins between the `startDate` and `endDate` on the specified day. The week count is not bounded by calendar `month` or calendar `year`. [source]
- ```cpp auto cursor = persons.aggregate(pipeline); ``` [source]
- ```php $cursor = $persons->aggregate($pipeline); ``` [source]
- Remote client connections are shown in the log under the "remote" key in the attribute object. The following counts all unique connections over the course of the log file and presents them in descending order by number of occurrences: [source]
- - Operation Count for all operation types [source]
- - Uses [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) to group by director, count movies, and compute `stdDevRating` using `$stdDevPop` on `imdb.rating`. [source]
- Establishing a cursor on all targeted shards. [source]
- | Parameter | Type | Description | | --- | --- | --- | | options | document | Optional. Extra options that affect the count behavior. | [source]
- [`db.collection.estimatedDocumentCount()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimateddocumentcount.md#mongodb-method-db.collection.estimatedDocumentCount) does not take a query filter and instead uses metadata to return the count for a collection. [source]
- - The document count is calculated by executing the [aggregation pipeline](https://www.mongodb.com/docs/manual/core/aggregation-pipeline.md#std-label-aggregation-pipeline) in the view definition. [source]
- | Field | Description | | --- | --- | | `"$ownOps"` | Boolean. If set to `true`, returns information on the current user's operations only. On [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instances, users are always authorized to run `currentOp` with `"$ownOps": true` to view their own operations. See [access control.](https://www.mongodb.com/docs/manual/reference/command/currentop.md#std-label-currentOp-access-control) | | `"$all"` | Boolean. If set to `true`, returns information on all operations, including operations on idle connectio [source]
- MongoDB also provides an equivalent [`db.collection.count()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#mongodb-method-db.collection.count) as an alternative to the `db.collection.find(<query>).count()` construct. [source]
- Retrieve the fragments from `myChangeStreamCursor` using the [`next()`](https://www.mongodb.com/docs/manual/reference/method/cursor.next.md#mongodb-method-cursor.next) method and store the fragments in objects named `firstFragment`, `secondFragment`, and `thirdFragment`: [source]
- Applies a `function` to each document visited by the cursor and collects the return values from successive applications of the `function` into a `Cursor` object. [source]
- | Parameter | Type | Description | | --- | --- | --- | | `function` | function | A function to apply to each document visited by the cursor. | [source]
- [`cursor.map()`](https://www.mongodb.com/docs/manual/reference/method/cursor.map.md#mongodb-method-cursor.map) returns a `Cursor` object. Note that `.map()` only converts the type, it does not create a new cursor. You can convert the `Cursor` object to an `Array` with `.toArray()`. [source]
- `cursor.tryNext()` is a special case of the [`cursor.next()`](https://www.mongodb.com/docs/manual/reference/method/cursor.next.md#mongodb-method-cursor.next) method that returns the next element in the iteration if available or else `null`. [source]
- [`maxTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxtimems.md#mongodb-method-cursor.maxTimeMS) is not related to the `NoCursorTimeout` query flag. [`maxTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxtimems.md#mongodb-method-cursor.maxTimeMS) relates to processing time, while `NoCursorTimeout` relates to idle time. A cursor's idle time does not contribute towards its processing time. [source]
- Starting in MongoDB 9.0, the COUNT_SCAN, GEO_NEAR_2D, GEO_NEAR_2DSPHERE, and UPDATE stages also report this field. [source]
- COUNT_SCAN, GEO_NEAR_2D, GEO_NEAR_2DSPHERE, GROUP, SORT, UPDATE [source]
- A [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) that remains open as long as a connection to the MongoDB deployment remains open *and* the collection exists. See [Change Stream Events](https://www.mongodb.com/docs/manual/reference/change-events.md) for examples of change event documents. [source]
- - The [change stream cursor](https://www.mongodb.com/docs/manual/changestreams.md#std-label-changeStreams) remains open until one of the following occurs: - The cursor is explicitly closed. [source]
- - The connection to the MongoDB deployment closes or times out. See [Behavior](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursor-behaviors) for more information. [source]
- By default, the [change stream cursor](https://www.mongodb.com/docs/manual/changestreams.md#std-label-changeStreams) returns specific field changes/deltas for update operations. You can also configure the change stream to look up and return the current majority-committed version of the changed document. Depending on other write operations that may have occurred between the update and the lookup, the returned document may differ significantly from the document at the time of the update. [source]
- MongoDB provides multiple ways to iterate on a cursor. [source]
- The [`cursor.hasNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hasnext.md#mongodb-method-cursor.hasNext) method blocks and waits for the next event. To monitor the `watchCursor` cursor and iterate over the events, use `hasNext()` like this: [source]
- The [`cursor.tryNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.trynext.md#mongodb-method-cursor.tryNext) method is non-blocking. To monitor the `watchCursor` cursor and iterate over the events, use `tryNext()` like this: [source]
- The following operation opens a change stream cursor against the `data.sensors` collection: [source]
- Iterate the cursor to check for new events. Use the [`cursor.isClosed()`](https://www.mongodb.com/docs/manual/reference/method/cursor.isclosed.md#mongodb-method-cursor.isClosed) method with the [`cursor.tryNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.trynext.md#mongodb-method-cursor.tryNext) method to ensure the loop only exits if the change stream cursor is closed *and* there are no objects remaining in the latest batch: [source]
- The following operation opens a change stream cursor against the `data.sensors` collection using the `fullDocument : "updateLookup"` option. [source]
- The following example creates a change stream cursor for the `temperatureSensor` collection using `fullDocumentBeforeChange: "whenAvailable"`: [source]
- - The `while` loop runs until the cursor is closed. [source]
- The following example creates a change stream cursor for the `temperatureSensor` collection using `fullDocument: "whenAvailable"`: [source]
- The following operation opens a change stream cursor against the `data.sensors` collection using an aggregation pipeline to filter only `insert` events: [source]
- Iterate the cursor to check for new events. Use the [`cursor.isClosed()`](https://www.mongodb.com/docs/manual/reference/method/cursor.isclosed.md#mongodb-method-cursor.isClosed) method with the [`cursor.hasNext()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hasnext.md#mongodb-method-cursor.hasNext) method to ensure the loop only exits if the change stream cursor is closed *and* there are no objects remaining in the latest batch: [source]
- The change stream cursor only returns change events where the `operationType` is `insert`. For complete documentation on change stream output, see [Change Stream Events.](https://www.mongodb.com/docs/manual/reference/change-events.md#std-label-change-stream-output) [source]
- Every document returned by a change stream cursor includes a resume token as the `_id` field. To resume a change stream, pass the entire `_id` document of the change event you want to resume from to either the `resumeAfter` or `startAfter` option of [`watch()`.](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#mongodb-method-db.collection.watch) [source]
- The following operation resumes a change stream cursor against the `data.sensors` collection using a resume token. This assumes that the operation that generated the resume token has not rolled off the cluster's oplog. [source]
- The [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method returns a [cursor](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md) to the matching documents. [source]
- The Find operation opens a [cursor](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md) to the matching documents of the collection based on the find query. [source]
- The [mongoc\_collection\_find\_with\_opts](https://mongoc.org/libmongoc/current/mongoc_collection_find_with_opts.html) method returns a [cursor](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md) to the matching documents. [source]
- The [`pymongo.collection.Collection.find`](https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.find) method returns a [cursor](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md) to the matching documents. See the PyMongo documentation for [iterating over a cursor.](https://pymongo.readthedocs.io/en/stable/tutorial.html#querying-for-more-than-one-document) [source]
- The [`pymongo.asynchronous.collection.AsyncCollection.find`](https://pymongo.readthedocs.io/en/stable/api/pymongo/asynchronous/collection.html#pymongo.asynchronous.collection.AsyncCollection.find) method returns a [cursor](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md) to the matching documents. [source]
- The [`MongoDB\\Collection::find()`](https://www.mongodb.com/docs/php-library/upcoming/reference/method/MongoDBCollection-find.md#mongodb-phpmethod-phpmethod.MongoDB-Collection--find--) method returns a [cursor](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md) to the matching documents. See the MongoDB PHP Library documentation for [iterating over a cursor.](https://www.mongodb.com/docs/php-library/upcoming/crud/query/cursor.md#std-label-php-cursors-iterate) [source]
- The [MongoCollection.Find()](https://mongodb.github.io/mongo-csharp-driver/2.10/apidocs/html/M_MongoDB_Driver_MongoCollection_1_Find.htm) method returns a [cursor](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md) to the matching documents. See the MongoDB .NET/C# Driver documentation for [iterating over a cursor](https://www.mongodb.com/docs/drivers/csharp/v2.19/fundamentals/crud/read-operations/retrieve/#find-multiple-documents). [source]
- The [Collection.Find](https://godoc.org/github.com/mongodb/mongo-go-driver/mongo#Collection.Find) function returns a [Cursor](https://godoc.org/github.com/mongodb/mongo-go-driver/mongo#Cursor) to the matching documents. See the [Cursor](https://godoc.org/github.com/mongodb/mongo-go-driver/mongo#Cursor) documentation for more information. [source]
- | Property | Data type | Description | | --- | --- | --- | | `x-bsonType` | string or array | BSON (Binary Javascript Object Notation) type of this field. | | `x-metadata` | document | Document containing metadata about the field. | | `hasDuplicates` | boolean | `true` if a single value appears multiple times in this field. Otherwise `false`. | | `probability` | float | Probability that the field exists in a random document. | | `count` | integer | Number of documents from the sample that have this field. | | `x-sampleValues` | array | Sample values as Expanded JSON. Sample values are limited [source]
- Starting in MongoDB 5.0, for an uncorrelated subquery in a [`$lookup`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#mongodb-pipeline-pipe.-lookup) pipeline stage containing a [`$sample`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) stage, the [`$sampleRate`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/samplerate.md#mongodb-expression-exp.-sampleRate) operator, or the [`$rand`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rand.md#mongodb-expression-exp.-ran [source]
- [`cursor.isExhausted()`](https://www.mongodb.com/docs/manual/reference/method/cursor.isexhausted.md#mongodb-method-cursor.isExhausted) returns `false` if documents remain in the current document batch read by the cursor. Otherwise, returns `true`. [source]
- - documents remain in a change stream cursor, use [`cursor.tryNext()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.trynext.md#mongodb-method-cursor.tryNext) [source]
- - a change stream cursor is closed, use [`cursor.isClosed()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.isclosed.md#mongodb-method-cursor.isClosed) [source]
- 2. Create a cursor variable [source]
- ```javascript sensorCursor.count() ``` [source]
- 4. Return the first document from the cursor [source]
- 6. Return the next document from the cursor [source]
- 7. Attempt to return the next document from the cursor [source]
- The `cursor.addOption()` method has the following parameter: [source]
- | Parameter | Type | Description | | --- | --- | --- | | `flag` | flag | For [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh), you can use the cursor flags listed below. For the driver-specific list, see your [driver documentation.](https://www.mongodb.com/docs/drivers/) | [source]
- [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) provides several additional cursor flags to modify the behavior of the cursor. [source]
- The example in this section uses [`$tsSecond`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tssecond.md#mongodb-expression-exp.-tsSecond) in a [change stream cursor](https://www.mongodb.com/docs/manual/changestreams.md#std-label-changeStreams) to monitor changes to a collection. [source]
- - Uses [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) to filter for movies with a `rated` value of `G`, `PG`, `PG-13`, or `R` and an integer IMDb vote count. [source]
- ```csharp .Group( id: o => o.Products.ProductId, group: g => new { ProductId = g.Key, Product = g.First().Products.Name, TotalValue = g.Sum(o => o.Products.Price), Quantity = g.Count() } ); [source]
- For the database command, see the [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) command. [source]
- Returns the count of documents that would match a [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) query for the collection or view, without performing the find operation. [source]
- The `db.collection.count()` method has the following form: [source]
- | Parameter | Type | Description | | --- | --- | --- | | `query` | document | The query selection criteria. | | `options` | document | Optional. Extra options for modifying the count. | [source]
- `count()` is equivalent to the `db.collection.find(query).count()` construct. [source]
- Instructs the server to avoid closing a cursor automatically after a period of inactivity. [source]
- The [`noCursorTimeout()`](https://www.mongodb.com/docs/manual/reference/method/cursor.nocursortimeout.md#mongodb-method-cursor.noCursorTimeout) method has the following prototype form: [source]
- estimatedDocumentCount() takes no filter and returns the count from collection metadata, so it does not scan; on a view there is no metadata and it runs the view pipeline, so it is not fast there. [source]
- For counts read many times per second, a counter document maintained with $inc avoids repeated counting, at the cost of drift (reconcile periodically with countDocuments()) and extra write logic. [source]
Related concepts
- cursor — is a part of MongoDB counts, distinct, cursors and read-path tuning
- count — is a part of MongoDB counts, distinct, cursors and read-path tuning
- index — is a related of MongoDB counts, distinct, cursors and read-path tuning
- read preference — is a related of MongoDB counts, distinct, cursors and read-path tuning
- query shape — is a related of MongoDB counts, distinct, cursors and read-path tuning
- sharded query targeting — is a part of MongoDB counts, distinct, cursors and read-path tuning
- query optimization — is a hypernym of MongoDB counts, distinct, cursors and read-path tuning
Children
- No children recorded.