<!-- llms-explorer concept facts · https://llms-explorer.com/tree/mongodb-query-shape-optimization-sort-pagination-operators-and-sharded-targeting/ · pack 2026-10-19 · ~197089 tokens -->

# MongoDB Query Shape Optimization: Sort, Pagination, Operators and Sharded Targeting

> The shape of a find or aggregate query decides whether the planner can use an index: index-backed sorts avoid the blocking SORT stage and its memory limit, keyset pagination replaces deep skip, $regex, $ne, $nin, $where and $expr constrain index bounds, $in and $or become point bounds or index unions, projection can make a query covered, count, distinct, $sample and cursor batchSize/maxTimeMS carry their own costs, and a sharded query is targeted only when the shard key is in the filter. Compiled from MongoDB manual and Atlas pages plus the run's verified claims.

Parent: [MongoDB Performance Troubleshooting](https://llms-explorer.com/tree/mongodb-performance-troubleshooting/) · 9 facets · 2427 facts · page: https://llms-explorer.com/tree/mongodb-query-shape-optimization-sort-pagination-operators-and-sharded-targeting/

## 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](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- - Indexes are not used for comparisons where the `let` operand resolves to an empty or missing value. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#expr-in-lookup-operations)
- The query does not return the array field (meaning the array is not included in the query projection). This means that to cover a query, the multikey index must be compound. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey/)
- - The query does not return the array field (meaning the array is not included in the query projection). This means that to cover a query, the multikey index must be [compound.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#std-label-compound_multikey_indexes) — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#covered-queries)
- A query shape is a set of specifications that group similar queries together. Specifications can include filters, sorts, projections, aggregation pipeline stages, a namespace, and others. Queries that have similar specifications have the same query shape. — [source](https://www.mongodb.com/docs/manual/core/query-shapes/)
- For instance, the inequality operators $nin and $ne are not very selective since they often match a large portion of the index. As a result, in many cases, a $nin or $ne query with an index may perform no better than a $nin or $ne query that must scan all documents in a collection. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- Further optimization can occur if the regular expression is a "prefix expression", which means that all potential matches start with the same string. This allows MongoDB to construct a "range" from that prefix and only match values from the index within the specified range. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#case-sensitive-queries)
- A regular expression is a "prefix expression" if it starts with a caret (`^`) or a left anchor (`\A`), followed by a string of simple symbols. For example, the regex `/^abc.*/` is optimized to match only the values from the index that start with `abc`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#case-sensitive-queries)
- $sample is the first stage of the pipeline. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- Only present if the cursor is not idle. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- `myCount` is the output field that stores the count. You can specify another name for the output field. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#behavior)
- The document with `_id` equal to `3` is the only document that matched the [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) criteria. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#array-fields)
- The $in behavior change at 201 array elements is not guaranteed to stay the same for all MongoDB versions. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#save-a-cursor-with-let)
- A `batchSize` of `0` means that the cursor is established, but no documents are returned in the first batch. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md#definition)
- However, hashed distribution means that range-based queries on the shard key are less likely to target a single shard, resulting in more cluster-wide broadcast operations. — [source](https://www.mongodb.com/docs/manual/sharding/)
- 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](https://www.mongodb.com/docs/atlas/performance-advisor/access-with-mcp.md#about-the-mongodb-mcp-server)
- If `<value>` is a regular expression, MongoDB expands the statement to use the `$regex` operator `{ field: { $regex: <value> } }`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#match-a-regular-expression)
- $regex is a range operator. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)

## Structure and components

- When run on [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos), indexes can only cover queries on [sharded](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-shard) collections if the index contains the shard key. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#sharded-collections)
- On sharded collections queried through mongos, an index covers a query only if it contains the shard key; the manual states an _id-only exception, but that exception is disputed (see disagreements). — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- | 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](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- When an index [covers](https://www.mongodb.com/docs/manual/core/query-optimization.md#std-label-indexes-covered-queries) a query, MongoDB can both match the query conditions **and** return the results using only the index keys. MongoDB does not need to examine documents from the collection to perform any part of the query. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#covered-queries)
- Index filters are set with the [`planCacheSetFilter`](https://www.mongodb.com/docs/manual/reference/command/plancachesetfilter.md#mongodb-dbcommand-dbcmd.planCacheSetFilter) command and determine which indexes the planner evaluates for a [query shape](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-query-shape). A plan cache query shape consists of a combination of query, sort, and projection specifications. If an index filter exists for a given query shape, the planner only considers those indexes specified in the filter. — [source](https://www.mongodb.com/docs/manual/core/query-plans.md#index-filters)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#index-use)
- If using [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) with [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort), be sure to include at least one field in your sort that contains unique values, before passing results to [`skip()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#using-skip-with-sort)
- If an array field contains multiple documents with the same field name and the [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method includes a [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) on that repeating field, the returned documents may not reflect the sort order because the sort was applied to the elements of the array before the [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) projection ope — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#sorts-and-the-positional-operator)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#syntax)
- The `$text` operator assigns a score to each result document. The score represents the relevance of a document to a given query. The score can be part of a [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method specification as well as part of the projection expression. The `{ $meta: "textScore" }` expression provides information on the processing of the `$text` operation. See [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) projection operator for details on accessing t — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#text-score)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#opcounters)
- The preceding index is multikey because the `genres` field contains array values. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#covered-queries)
- - **In find**, the `{ $meta: "indexKey" }` expression is only available as part of the [projection](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-projection) document. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#availability)
- - All the fields in the query (both as specified by the application and as needed internally such as for sharding purposes) are part of an index. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#run-covered-queries)
- Because the index contains all fields required by the query, MongoDB can both match the [query conditions](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#std-label-read-operations-query-document) and return the results using only the index. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#performance)
- 1. The `movies` collection contains documents where the `metacritic` field is present in some documents and absent from others. Of the 21,349 documents, 6,964 have the `metacritic` field and 14,385 do not. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- 2. Before creating the index, validate that no documents in the collection violate the index constraints. If a collection is distributed across shards and a shard contains a chunk with duplicate documents, the create index operation may succeed on the shards without duplicates but not on the shard with duplicates. To avoid leaving inconsistent indexes across shards, you can issue the [`db.collection.dropIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.dropindex.md#mongodb-method-db.collection.dropIndex) from a [`mongos`](https://www.mongodb.com/docs/manual/reference — [source](https://www.mongodb.com/docs/manual/tutorial/build-indexes-on-sharded-clusters.md#before-you-begin)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- When run on mongos, indexes can only cover queries on sharded collections if the index contains the shard key. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- | 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](https://www.mongodb.com/docs/compass/query-with-natural-language/compass-ai-assistant.md#database-tools)
- Specifies the number of "work units" performed by the query execution stage. Query execution divides its work into small units. A "work unit" might consist of examining a single index key, fetching a single document from the collection, applying a projection to a single document, or doing a piece of internal bookkeeping. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- - 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](https://www.mongodb.com/docs/atlas/tutorial/query-profiler.md#find-slow-queries-with-the-query-profiler)
- 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](https://www.mongodb.com/docs/manual/core/index-sparse.md#sparse-index-and-incomplete-results)
- Contains information on the selection of the query plan by the [query optimizer.](https://www.mongodb.com/docs/manual/core/query-plans.md#std-label-read-operations-query-optimization) — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- If query settings are set, `querySettings` contains details about the query settings that are applied to the query shape. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- [Match expression operators](https://www.mongodb.com/docs/manual/reference/mql/query-predicates.md#std-label-query-projection-operators-top) also increment as part of an aggregation pipeline [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage. If the `$match` stage uses the [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) operator, the counter for `$expr` increments, but the component counters do not increment. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- - Only contain one second of temporal resolution, so [ObjectId](https://www.mongodb.com/docs/manual/reference/bson-types.md#std-label-objectid) values created within the same second do not have a guaranteed ordering, and — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#descending-order)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#output)
- The second case occurs when the merge part of the split pipeline contains a stage which may write temporary data to disk, such as $group, and the client has specified allowDiskUse:true. In this case, assuming that there are no other stages in the merge pipeline which require the primary shard, the merge runs on a randomly-selected shard in the set of shards targeted by the aggregation. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- The following example returns movies where `runtime` is greater than `1000` minutes and `title` does not start with the letter `T`. Because `$not` also matches documents that don't contain the `title` field, the query returns movies even when title data is unavailable: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#regular-expressions)
- This example counts the number of documents in the `movies` collection where the `directors` field contains `"David Lynch"`: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#count-all-documents-that-match-a-query)
- Although the array field `grades` may contain multiple elements that are greater than or equal to `85`, the [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) projection operator returns only the first matching element from the array. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#project-array-values)
- The [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection of an array in an nested document no longer returns the other fields in the nested document when the projection is part of an inclusion projection. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#slice-of-embedded-array)
- If the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection is part of an exclusion projection, the operation continues to return the other fields in the nested document. That is, the following projection is an exclusion projection. The projection excludes the `_id` field and the elements in the `colors` array that fall outside the specified slice and returns all other fields. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#slice-of-embedded-array)
- When run on a `mongos` that is part of a sharded cluster: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#sharded-cluster-mongos-query-analyzer-output)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- The `originatingCommand` field contains the full command object (e.g. `find` or `aggregate`) which originally created the cursor. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- be sure to include at least one field in your sort that contains unique values, before passing results to the [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) stage. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#using-skip-with-sorted-results)
- Passes a document to the next stage that contains a count of the number of documents input to the stage. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#definition)
- `<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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#syntax)
- 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](https://www.mongodb.com/docs/manual/reference/database-profiler/)
- The [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) operator limits the contents of an `<array>` field from the query results to contain only the **first** element matching the [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) condition. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#definition)
- - For the document with `_id` equal to `1`, the `students` array contains multiple elements with the `school` field equal to `102`. However, the [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) projection returns only the first matching element from the array. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#zipcode-search)
- - The document with `_id` equal to `3` does not contain the `students` field in the result since no element in its `students` array matched the [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) condition. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#zipcode-search)
- The document with `_id` equal to `3` does not contain the `students` field since no array element matched the [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) criteria. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- The command returns a document that contains the cursor information and the next batch. — [source](https://www.mongodb.com/docs/manual/reference/command/getMore.md#output)
- | 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](https://www.mongodb.com/docs/manual/reference/command/getMore.md#output)
- As part of establishing a TCP Fast Open (TFO) connection, the client submits a valid TFO cookie to the `mongod/mongos` *before* completion of the standard TCP 3-way handshake. The `mongod/mongos` keeps a queue of all such pending TFO connections. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- | 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](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- Configures a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance to preload the routing table for a sharded cluster on startup. With this setting enabled, the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) caches the cluster-wide routing table for each sharded collection as part of its startup procedure, before it begins accepting client connections. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- Configures a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance to prewarm its connection pool on startup. With this parameter enabled, the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) attempts to establish [`ShardingTaskExecutorPoolMinSize`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.ShardingTaskExecutorPoolMinSize) network connections to each shard server as part of its startup procedure, before it begins accepting client connections. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#error-response)
- - The `{ $meta: "textScore" }` expression can be a part of the [projection](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-projection) document to include the text score metadata. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#usage-in-projection)
- A modified cursor object that contains the document fields and the appended `$recordId` field. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.showRecordId.md#definition)
- If an aggregation pipeline contains multiple projection or `$match` stages, MongoDB performs this optimization for each `$match` stage, moving each `$match` filter before all projection stages that the filter does not depend on. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#project-or-unset-or-addfields-or-set-match-sequence-optimization)
- When a [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) immediately follows another [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip), the two stages can coalesce into a single [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) where the skip amount is the *sum* of the two initial skip amounts. For example, a pipeline contains the following sequence: — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#skip-skip-coalescence)
- As part of making [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) and [`findAndModify()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.findandmodify.md#mongodb-method-db.collection.findAndModify) projection consistent with aggregation's [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage, — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#projection)
- | Name | Type | Required | Description | | --- | --- | --- | --- | | --apiKey | string | false | Datadog API Key, Opsgenie API Key, or VictorOps API key. Required if the notificationType is DATADOG, OPS_GENIE, or VICTOR_OPS, respectively. | | --enabled | | false | Flag that indicates whether to enable the alert configuration. | | --event | string | false | Type of event that triggered the alert. To learn which values the CLI accepts, see the Enum for eventTypeName in the Atlas Admin API spec: [https://dochub.mongodb.org/core/atlas-event-names.](https://dochub.mongodb.org/core/atlas-event-name — [source](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-alerts-settings-create.md#options)
- A document that contains metrics about [`mongos`.](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- [`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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- A document that contains data regarding cursor state and use. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- A document that contains data regarding open cursors. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The total number of logical bytes that `mongod` or `mongos` instances have *received* over network connections that they have initiated to other nodes/services. Logical bytes are the exact number of bytes that a given file contains. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- The total number of logical bytes that `mongod` or `mongos` instances have *sent* over network connections that they have initiated to other nodes/services. Logical bytes correspond to the number of bytes that a given file contains. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- The total number of logical bytes that the server has *received* over network connections initiated by clients or other `mongod` or `mongos` instances. Logical bytes are the exact number of bytes that a given file contains. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- The total number of logical bytes that the server has *sent* over network connections initiated by clients or other `mongod` or `mongos` instances. Logical bytes correspond to the number of bytes that a given file contains. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- Total number of network requests targeted by the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) as part of its transactions. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#mongod)
- A list of IP addresses/CIDR ([Classless Inter-Domain Routing](https://tools.ietf.org/html/rfc4632)) ranges against which the `mongod` validates authentication requests from other members of the replica set and, if part of a sharded cluster, the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances. The `mongod` verifies that the originating IP is either explicitly in the list or belongs to a CIDR range in the list. If the IP address is not present, the server does not authenticate the `mongod` or [`mongos`.](https://www.mongodb.com/docs — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#core-options)
- 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](https://www.mongodb.com/docs/atlas/data-federation/query/view-query-history.md)
- The [projection](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#std-label-find-projection) parameter specifies which fields to return. The parameter contains either include or exclude specifications, not both, unless the exclude is for the `_id` field. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#projections)
- - Deploy [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) routers in accordance with the [Production Configuration](https://www.mongodb.com/docs/manual/core/sharded-cluster-components.md#std-label-sc-production-configuration) guidelines. — [source](https://www.mongodb.com/docs/manual/administration/production-checklist-operations.md#sharding)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortByCount.md#definition)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#bucket-by-year-and-filter-by-bucket-results)
- This operation matches documents with `$text`, then sorts descending by `"textScore"` metadata and by `year`, and returns the first five results. The `score` field name in the sort document is ignored by the query system. The projection doesn't include the `"textScore"` metadata and does not return the metadata as part of the matching documents. See [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) for more information. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#text-score-metadata-sort)
- While automatic encryption does not encrypt the getMore command, the response to the command may contain encrypted field values. — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/supported-operations.md#supported-read-and-write-commands)
- Execution metrics such as totalExecMicros contain information for the most recent operation (cursor creation, getMore, or cursor close). — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- For fields that contain arrays, MongoDB provides the following projection operators for manipulating arrays: [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch), [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice), and [`$`.](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- - 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto.md#definition)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind.md#unwind-multiple-array-fields)
- | Aspect | Atlas Core | Atlas Infinite | | --- | --- | --- | | Architecture | Compute and storage run on the same node. Each data-bearing node runs on a virtual machine with attached storage. | Compute and storage run as independent layers. MongoDB manages the storage layer separately from the compute nodes. | | Compute scaling | You change compute capacity by selecting a different cluster tier. Atlas restarts the cluster's nodes when you change the tier, with no downtime on dedicated clusters. | You scale the cluster tier independently of storage. Scaling doesn't move your data, so it is fast — [source](https://www.mongodb.com/docs/atlas/index.md#compare-editions)
- For example, the following JSON object represents a command attribute that contains 5000 elements in the $in field without truncation. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- Messages related to database commands, such as count. To specify the log level for COMMAND components, use the systemLog.component.command.verbosity setting. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- Messages related to sharding activities, such as the startup of the mongos. To specify the log level for SHARDING components, use the systemLog.component.sharding.verbosity setting. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- In some cases, when the shard key or a prefix of the shard key is a part of the query, the mongos performs a targeted operation, routing queries to a subset of shards in the cluster. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- A range of shard keys whose values are "close" are more likely to reside on the same chunk. This allows for targeted operations as a mongos can route the operations to only the shards that contain the required data. — [source](https://www.mongodb.com/docs/manual/sharding/)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#examples)
- The most common practice is to run `mongos` instances on the same systems as your application servers, but you can maintain `mongos` instances on the shards or on other dedicated resources. See also [Number of `mongos` and Distribution.](https://www.mongodb.com/docs/manual/core/sharded-cluster-components.md#std-label-sharded-cluster-components-distribution) — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md)
- If `field` has an array, the `$in` operator selects the documents whose `field` has an array that contains at least one element that matches a value in the specified array. For example, `<value1>`, `<value2>`, and so on. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#syntax)
- If you specify a `projection` parameter, [`findOne()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.findone.md#mongodb-method-db.collection.findOne) returns a document that only contains the `projection` fields. The `_id` field is always included unless you explicitly exclude it. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne.md#definition)
- The `projection` parameter specifies which fields to return. The parameter contains either include or exclude specifications, not both, unless the exclude is for the `_id` field. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne.md#with-a-projection)
- The following operation returns a document in the `movies` collection where the `cast` array contains `"Al Pacino"`. The projection returns all fields *except* the `_id` field, the `votes` field in the `imdb` embedded document, and the `fullplot` field: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne.md#return-all-but-the-excluded-fields)
- Provides regular expression (regex) pattern matching capability in aggregation expressions. The operator returns an array of documents that contains information on each match. If a match is not found, returns an empty array. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexFindAll.md#definition)
- [`$not`](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#mongodb-query-op.-not) performs a logical `NOT` operation on the specified `<operator-expression>` and selects the documents that do *not* match the `<operator-expression>`. This includes documents that do not contain the `field`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#definition)
- Provides regular expression (regex) pattern matching capability in aggregation expressions. If a match is found, returns a document that contains information on the *first* match. If a match is not found, returns null. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexFind.md#definition)
- The exception in returning documents that do not contain the field in the [`$nor`](https://www.mongodb.com/docs/manual/reference/operator/query/nor.md#mongodb-query-op.-nor) expression is when the [`$nor`](https://www.mongodb.com/docs/manual/reference/operator/query/nor.md#mongodb-query-op.-nor) operator is used with the [`$exists`](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#mongodb-query-op.-exists) operator. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nor.md#nor-and-additional-comparisons)
- When `$expr` appears in a [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage that is part of a [`$lookup`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#mongodb-pipeline-pipe.-lookup) subpipeline, `$expr` can refer to `let` variables defined by the `$lookup` stage. For an example, see [Use Multiple Join Conditions and a Correlated Subquery.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#std-label-lookup-multiple-joins) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#expr-in-lookup-operations)
- `$expr` can contain expressions that compare fields from the same document. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#compare-two-fields-from-a-single-document)
- The [`$exists`](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#mongodb-query-op.-exists) operator matches documents that contain or do not contain a specified field, including documents where the field value is `null`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#definition)
- When `<boolean>` is true, [`$exists`](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#mongodb-query-op.-exists) matches the documents that contain the field, including documents where the field value is `null`. If `<boolean>` is false, the query returns only the documents that do not contain the field. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#syntax)
- The following example queries for all documents where the `cast` array contains at least one element that matches the regular expression `^A`: — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-an-array-for-an-element)
- The following example queries for documents where the `cast` array contains elements that in some combination satisfy the query conditions. One element can satisfy the `$regex: "^A"` condition and another element can satisfy the `$ne: "Adam Sandler"` condition, or a single element can satisfy both: — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-an-array-with-compound-filter-conditions-on-the-array-elements)
- The following example queries for documents where the `cast` array contains at least one element that both matches the regular expression `^A` and is not equal to `"Adam Sandler"`: — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-for-an-array-element-that-meets-multiple-criteria)
- The following example uses the [`$nin`](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#mongodb-query-op.-nin) operator to query for all documents where the `genres` field does not contain `Drama`: — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-an-array-for-an-element)
- The following example queries for documents where the `cast` array contains elements that in some combination satisfy the query conditions. The following filter uses the [`$regex`](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#mongodb-query-op.-regex) and [`$eq`](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#mongodb-query-op.-eq) operators to return documents where a single array element ends in `Olsen` and another element equals `Mary-Kate Olsen` or a single element that satisfies both conditions: — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-an-array-with-compound-filter-conditions-on-the-array-elements)
- The following example uses the [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/query/elemmatch.md#mongodb-query-op.-elemMatch) and [`$ne`](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#mongodb-query-op.-ne) operators to query for documents where `languages` contains at least one element that is both not `null` and does not equal `English`: — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-for-an-array-element-that-meets-multiple-criteria)
- [`--ldapUserToDNMapping`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--ldapUserToDNMapping) expects a quote-enclosed JSON-string representing an ordered array of documents. Each document contains a regular expression `match` and either a `substitution` or `ldapQuery` template used for transforming the incoming username. — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#ldap-authentication-or-authorization-options)
- `$ne` selects documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#definition)
- The following example returns movies where `runtime` is greater than `1000` minutes and `rated` is not equal to `"G"`. Because `$ne` also matches documents that don't contain the `rated` field, the query returns movies even when the rating data is unavailable: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#match-document-fields-that-are-not-equal)
- [`updateMany()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.updatemany.md#mongodb-method-db.collection.updateMany) also selects a document when the document does not contain the field [`$nin`](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#mongodb-query-op.-nin) is matching on. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#select-on-elements-not-in-an-array)
- The `{ metacritic : { $exists: false } }` query matches documents that do not contain the `metacritic` field: — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- The `{ item : { $exists: False } }` query matches documents that do not contain the `item` field: — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- The `[ item => [ $exists => false ] ]` query matches documents that do not contain the `item` field: — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- The `{ item => { $exists => false } }` query matches documents that do not contain the `item` field: — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- The `{ item, { $exists, BCON_BOOL (false) } }` query matches documents that do not contain the `item` field: — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- The `bson.D{{"item", bson.D{{"$exists", false}}}}` query matches documents that do not contain the `item` field: — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- If the `$regex` pattern doesn't contain an anchor, the pattern matches against the whole string. For example: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#multiline-match-for-lines-starting-with-specified-pattern)
- The following example uses the regular expression `"(?i)a(?-i)bc"` to match `sku` field strings that contain: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#use-a-regular-expression-to-match-case-in-strings)

## 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](https://www.mongodb.com/docs/manual/core/index-sparse.md#sparse-index-and-incomplete-results)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#inaccurate-counts-without-query-predicate)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#sharded-clusters)
- A query that exceeds either 100 megabytes or the available memory spills to disk. It writes intermediate data to storage to save memory, which can cause lowered performance. Use the [`allowDiskUseByDefault`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.allowDiskUseByDefault) parameter or [`cursor.allowDiskUse()`](https://www.mongodb.com/docs/manual/reference/method/cursor.allowdiskuse.md#mongodb-method-cursor.allowDiskUse) method to configure this behavior. — [source](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#query-spill)
- Offset pagination is inconsistent under concurrent writes: inserts or deletes between requests cause duplicate or missing items. Keyset is more stable for changes before the current page but not immune; mutable sort fields can still cause duplicates or misses. — [source](https://begriffs.com/posts/2016-03-30-five-ways-to-paginate.html)
- - 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](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#behavior)
- Query optimization improves the efficiency of read operations by reducing the amount of data that query operations need to process. Use indexes, projections, and query limits to enhance query performance and reduce resource consumption. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- 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](https://www.mongodb.com/docs/manual/core/query-optimization.md#use-index-hints)
- 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](https://www.mongodb.com/docs/manual/core/read-preference.md)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.itcount.md#definition)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#parameters)
- Multikey indexes can cover queries over the non-array fields if the index tracks which field or fields cause the index to be multikey. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#multikey-covering)
- When an index covers a query, the explain result has an `IXSCAN` stage that is **not** a descendant of a `FETCH` stage. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#covered-queries)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- When a shard receives a query, it uses the most efficient index available to fulfill that query. The index used may be either the [shard key index](https://www.mongodb.com/docs/manual/core/sharding-shard-key-indexes.md#std-label-sharding-shard-key-indexes) or another eligible index present on the shard. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#index-use)
- When $or clauses are equality checks on the same field, the MongoDB manual says to use $in instead; $in runs one IXSCAN in total, whereas $or runs one IXSCAN per condition. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/or/)
- A compound index often outperforms a union of single-field indexes for an $or with shared extra filters, because a union must merge and deduplicate results. This is asserted by a blog and a forum reply without a controlled benchmark. — [source](https://oneuptime.com/blog/post/2026-03-31-mongodb-index-for-or-queries/view)
- When you sort based on an array field that is indexed with a multikey index, the query plan includes an in-memory sort stage unless both of the following are true: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey/)
- When you sort based on an array field that is indexed with a [multikey index](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#std-label-index-type-multikey), the query plan includes an [in-memory sort](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-in-memory-sort) stage unless both of the following are true: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#sorting)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.readConcern.md#linearizable-read-concern-performance)
- 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](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- 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](https://www.mongodb.com/docs/manual/core/query-plans.md#index-filters)
- If the collection has an index that includes the sort fields, MongoDB can use that index to obtain the results of a sort operation. In $or queries, MongoDB may use multiple indexes to support a single sort operation, because each clause of the $or expression can use its own index. — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/query/or.md#or-and-sort-operations)
- - 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](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#per-operation-memory-limit)
- Each index suggestion includes an Average Query Targeting score indicating how many documents were read for every document returned for the index's corresponding query shapes. A score of 1 represents very efficient query shapes because every document read matched the query and was returned with the query results. All suggested indexes represent an opportunity to improve query performance. — [source](https://www.mongodb.com/docs/atlas/performance-advisor.md#query-targeting)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#index-use)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#interaction-with-index-selection)
- 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](https://www.mongodb.com/docs/atlas/reference/alert-resolutions/query-targeting.md#common-triggers)
- When you use `$sort` on a sharded cluster, each shard sorts its result documents using an index where available. Then the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) or one of the shards performs a streamed merge sort. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#sort-index-use)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#interaction-with-index-selection)
- A covered query is a query that can be satisfied entirely using an index and doesn't have to examine any documents. An index covers a query when all of the following apply: — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#access-path-counters)
- When executing $or queries with a sort(), MongoDB can use indexes that support the $or clauses. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/or/)
- 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](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- The number of times that we had to seek the index cursor to a new position in order to complete the index scan. — [source](https://www.mongodb.com/docs/manual/reference/explain-results/)
- `$in` compares each parameter to each document in the collection, which can cause performance issues. To improve performance, create an index on the `field` you want to query. An index allows MongoDB to create bounds for each `$in` element and search more efficiently. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#syntax)
- 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](https://oneuptime.com/blog/post/2026-03-31-mongodb-index-for-count-operations/markdown)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#inaccurate-counts-without-query-predicate)
- - 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](https://www.mongodb.com/docs/manual/reference/operator/query/nearSphere.md#sort-operation)
- | Unique Index Key Pattern | Update Operation | Result | | --- | --- | --- | | `{ name : 1 }` | `db.people.updateOne( { name: "Andy" }, { $inc: { score: 1 } }, { upsert: true } )` | The `score` field of the matched document is incremented by 1. | | `{ name : 1 }` | `db.people.updateOne( { name: { $ne: "Joe" } }, { $set: { name: "Andy" } }, { upsert: true } )` | The operation fails because it modifies the field in the unique index key pattern (`name`). | | `{ name : 1 }` | `db.people.updateOne( { name: "Andy", email: "user@example.test" }, { $set: { active: false } }, { upsert: true } )` | The opera — [source](https://www.mongodb.com/docs/manual/reference/command/findAndModify.md#upsert-with-unique-index)
- Without a query predicate, `count()` returns results based on the collection's metadata, which may result in an incorrect count. In particular, — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#inaccurate-counts-without-query-predicate)
- - Create the indexes that the Performance Advisor suggests when they align with your [Indexing Strategies.](https://www.mongodb.com/docs/manual/applications/indexes/) — [source](https://www.mongodb.com/docs/atlas/analyze-slow-queries.md#best-practices-for-query-performance)
- As with any hash function, two different plan cache query shapes may result in the same hash value. However, the occurrence of hash collisions between different plan cache query shapes is unlikely. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- Returning paginated results in ascending order is similar to the previous, but uses [`$gt`](https://www.mongodb.com/docs/manual/reference/operator/query/gt.md#mongodb-query-op.-gt) with an *ascending* sort order: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#ascending-order)
- `$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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- When you use a [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage it should typically be the last stage in your pipeline, used to specify which fields to return to the client. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#project-stage-placement)
- Using a `$project` stage at the beginning or middle of a pipeline to reduce the number of fields passed to subsequent pipeline stages is unlikely to improve performance, because the database performs this optimization automatically. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#project-stage-placement)
- After the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) receives responses from all shards, it merges the data and returns the result document. The performance of a broadcast operation depends on the overall load of the cluster, as well as variables like network latency, individual shard load, and number of documents returned per shard. Whenever possible, favor operations that result in [targeted operation](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#std-label-sharding-mongos-targeted) over those that result i — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#broadcast-operations)
- When combining skip() with sort(), include a field with unique values (easiest: _id) in the sort. Duplicate sort values can yield inconsistent order across executions, especially while the collection receives writes. — [source](https://www.mongodb.com/docs/v8.2/reference/method/cursor.skip/)
- mongos performs a targeted operation when the query includes the shard key or a prefix of a compound shard key. For key {a:1,b:1,c:1} the usable prefixes are {a:1} and {a:1,b:1}. A query on {b:1} alone is not a prefix and broadcasts. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- `$sort` is a blocking stage, which causes the pipeline to wait for all input data to be retrieved for the blocking stage before processing the data. A blocking stage may reduce performance because it reduces parallel processing for a pipeline with multiple stages. A blocking stage may also use substantial amounts of memory for large data sets. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#performance)
- Examples of stages that can write temporary files to disk when [allowDiskUse](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#std-label-aggregate-cmd-allowDiskUse) is `true` are: — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#memory-restrictions)
- - Using `{ allowDiskUse: true }` to allow writing temporary files out to disk when `allowDiskUseByDefault` is set to `false` — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- - Using `{ allowDiskUse: false }` to prohibit writing temporary files out to disk when `allowDiskUseByDefault` is set to `true` — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- $expr with non-JavaScript aggregation operators is faster than $where because it runs no JavaScript. If custom JavaScript is unavoidable, $function inside $expr is preferred over $where. $where does not work inside $elemMatch (top-level documents only). — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#accumulator-operator)
- For example, `$group` operations of the following form can result in a `DISTINCT_SCAN`: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#retrieve-distinct-values)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#transactions)
- When an operation both sorts *and* [projects](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-projection) with the same fields, MongoDB sorts on the original field values before applying the projection. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#interaction-with-projection)
- When run without [localOps:true](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#std-label-currentOp-stage-localOps) on the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), the transaction information is per shard. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#mongos-composite-view-output)
- When run on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) without [localOps:true](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#std-label-currentOp-stage-localOps), the transaction information is per shard. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#mongos-per-shard-output)
- The date and time when the cursor was created. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- The date and time when the cursor was last used. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- The flag that indicates that the cursor doesn't timeout when idle; i.e. if the cursor has the `noTimeout` option set. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- - If true, the cursor does not time out when idle. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- - If false, the cursor times out when idle. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- Not available when running with `localOps: true` on [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) or when reporting on `idleCursors`. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- Not available when running with `localOps: true` on [`mongos`.](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- Only reported when running `$currentOp` on `mongos`. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#count-field)
- The preceding examples return the documents that have a `zipcode` value of `"63109"`, but these documents include only the `_id` field because the projection operation found no matching elements. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- When connected to a sharded cluster through [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), you can run the [`profile`](https://www.mongodb.com/docs/manual/reference/command/profile.md#mongodb-dbcommand-dbcmd.profile) command against any database. — [source](https://www.mongodb.com/docs/manual/reference/command/profile.md#behavior)
- The maximum number of seconds that the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) / [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) should wait for the OCSP response when verifying server certificates. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#oidcidentityproviders-fields)
- - 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](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- A [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance with the [`loadRoutingTableOnStartup`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.loadRoutingTableOnStartup) parameter enabled may experience longer startup times, but will result in faster servicing of initial client connections once started. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- When a query accesses a shard, a [chunk migration](https://www.mongodb.com/docs/manual/tutorial/migrate-chunks-in-sharded-cluster.md#std-label-migrate-chunks-sharded-cluster) or [DDL operation](https://www.mongodb.com/docs/manual/core/transactions-operations.md#std-label-transactions-operations-ddl) may already hold the critical section for the collection. If the query finds the critical section is taken, the shard waits until the critical section has been released. When the shard returns control to [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.m — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- A [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance with this parameter enabled may experience longer startup times, but will result in faster servicing of initial client connections once started. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#error-response)
- A MongoDB process can be either a mongod or mongos. — [source](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-api-monitoringAndLogs-listGroupProcesses.md)
- When you use countDocuments() in a transaction, the resulting count will not filter out any uncommitted multi-document transactions. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- Configures the cursor to display results in a format that is easy to read. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.pretty.md#definition)
- When $in is used alone, it is an equality operator that performs a series of equality matches. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#save-a-cursor-with-let)
- When aggregation operations run on multiple shards, the results are routed to the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) to be merged, except in the following cases: — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-sharded-collections.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#perform-a-count)
- You can also [export logs to an AWS S3 bucket](https://www.mongodb.com/docs/atlas/export-logs-external-sinks/). When you configure this feature, Atlas exports from `mongod`, `mongos`, and audit logs to an AWS (Amazon Web Services) S3 bucket every minute. — [source](https://www.mongodb.com/docs/atlas/architecture/current/monitoring-alerts.md#monitor-by-using-logs)
- Then the second [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) stage can coalesce into the first [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) stage and result in a single [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) stage where the skip amount `7` is the sum of the two initial limits `5` and `2`. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#skip-skip-coalescence)
- The current MongoDB process. Possible values are: [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) or [`mongod`.](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#instance-information)
- Counts how many write‑mode lock requests wait because another operation holds the lock. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#lockcontentionmetrics)
- A document that reports process-level counters for the [`$changeStream`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/changestream.md#mongodb-pipeline-pipe.-changeStream) options set on opened change streams. These counters are tracked 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) — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- A document that reports the number of change streams opened on this process, categorized by the scope that the change stream watches. These counters are tracked 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) — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- A document that reports throughput and cursor statistics for the change stream cursors that this process maintains. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The values update when a cursor closes and don't account for cursors that are still open. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The total number of change stream cursors that have closed in this process. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- A document that reports the number of change stream cursors currently open in this process. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of change stream cursors currently open in this process, including both idle and pinned cursors. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of times a change stream cursor failed to resume because the requested resume point is no longer available in the oplog. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- - The number of times a given authentication mechanism has been used to authenticate against the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#security)
- A document that reports on the number of times a given authentication mechanism has been used to authenticate against the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance. The values in the document distinguish standard authentication and speculative authentication.&#x20; — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#security)
- The fields in the `mechanisms` document depend on the configuration of the [`authenticationMechanisms`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.authenticationMechanisms) parameter. The `mechanisms` document includes a field for each authentication mechanism supported by your [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#security)
- - `true` when the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) / [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance's TLS/SSL certificate is associated with a certificate authority. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#security)
- When run on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), a document with data about the [transactions](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions) run on the instance. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#mongod)
- When inserting documents with monotonically increasing shard keys, all inserts belong to the same [chunk](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-chunk) on a single [shard](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-shard). The system eventually divides the chunk range that receives all write operations and migrates its contents to distribute data more evenly. However, at any moment the cluster directs insert operations only to a single shard, which creates an insert throughput bottleneck. — [source](https://www.mongodb.com/docs/manual/reference/limits.md#shard-key-limitations)
- - [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) includes a [Full Time Diagnostic Data Capture](https://www.mongodb.com/docs/manual/administration/full-time-diagnostic-data-capture.md#std-label-ftdc-stub) mechanism to assist MongoDB engineers with troubleshooting deployments. If this thread fails, it terminates the originating process. To avoid the most common failures, confirm that the user running the process has permissions to create the FTDC `diagnostic.data` directory. For `mongod` the directory is within [`storage.dbPath`](https://ww — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#considerations)
- Specifies a file location to store the process ID (PID) of the `mongod` process. The user running the `mongod` or `mongos` process must be able to write to this path. If the [`--pidfilepath`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--pidfilepath) option is not specified, the process does not create a PID file. Use this option mainly with the [`--fork`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--fork) option. — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#core-options)
- Allows the `mongod` to accept and create authenticated and non-authenticated connections to and from other `mongod` and [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances in the deployment. Used for performing rolling transition of replica sets or sharded clusters from a no-auth configuration to [internal authentication](https://www.mongodb.com/docs/manual/core/security-internal-authentication.md#std-label-inter-process-auth). Requires specifying a [internal authentication](https://www.mongodb.com/docs/manual/core/security-internal-a — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#core-options)
- For example, if using [keyfiles](https://www.mongodb.com/docs/manual/core/security-internal-authentication.md#std-label-internal-auth-keyfile) for [internal authentication](https://www.mongodb.com/docs/manual/core/security-internal-authentication.md#std-label-inter-process-auth), the `mongod` creates an authenticated connection with any `mongod` or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) in the deployment using a matching keyfile. If the security mechanisms do not match, the `mongod` uses a non-authenticated connection instead. — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#core-options)
- When you use db.collection.estimatedDocumentCount() in a transaction, the resulting count will not filter out any uncommitted multi-document transactions. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- The [config database](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-config-database) maintains a map identifying which documents are on which shards. The cluster updates this map as [chunks](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-chunk) move between shards. When a configuration server becomes inaccessible, certain sharding operations become unavailable, such as moving chunks and starting [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances. However, clusters remain accessible from alread — [source](https://www.mongodb.com/docs/manual/administration/monitoring.md#config-servers)
- Because inaccessible configuration servers can seriously impact the availability of a sharded cluster, you should monitor your configuration servers to ensure that the cluster remains well balanced and that [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances can restart. — [source](https://www.mongodb.com/docs/manual/administration/monitoring.md#config-servers)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#definition)
- When run on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), [`$currentOp`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-pipeline-pipe.-currentOp) returns the opids in the format of `"<shardName>:<opid on that shard>"`; e.g. — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#kill-write-operations)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- firstResponseExecMicros and totalExecMicros are always the same because stats are collected and updated for each getMore operation. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- When the cursor closes, lastExecutionMicros is 0. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- In sharded clusters, MongoDB records query statistics separately on each mongod and mongos when $queryStats is enabled. Shard servers also record statistics for queries that originate from mongos. These provide more complete shard-level metrics for queries that users route through mongos. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- hasSortStage is true when MongoDB must sort the documents after it receives the documents from a cursor. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- When a user creates a session on a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance, the record of the session initially exists only in-memory on the instance; i.e. the record is local to the instance. Periodically, the instance will sync its cached sessions to the [`system.sessions`](https://www.mongodb.com/docs/manual/reference/config-database.md#mongodb-data-config.system.sessions) collection in the `config` database, at which — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listLocalSessions.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/command/find.md#output)
- 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](https://www.mongodb.com/docs/manual/reference/command/find.md#find-cursor-behavior-on-views)
- When you need a subset of fields from documents, you can improve performance by returning only the fields you need. Projections reduce network traffic and processing time. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- Hashed indexing is ideal for shard keys with fields that change [monotonically](https://www.mongodb.com/docs/manual/core/sharding-choose-a-shard-key.md#std-label-shard-key-monotonic) like [ObjectId](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-ObjectId) values or timestamps. When you use [ranged sharding](https://www.mongodb.com/docs/manual/core/ranged-sharding.md#std-label-sharding-ranged) with a monotonically increasing shard key value, the chunk with an upper bound of [`MaxKey`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Max — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-hashed.md#use-cases)
- - `firstResponseExecMicros` and `totalExecMicros` are always the same because stats are collected and updated for each `getMore` operation. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#change-streams)
- - 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](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#stable-api)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.tailable.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.tailable.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.objsLeftInBatch.md)
- - Because the 31st is a Sunday and it is between `startDate` and `endDate`, one `week` is added to the count. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateDiff.md#weeks-per-month)
- - The `week` count is incremented even when a calendar week finishes after `endDate` or in the next calendar period. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateDiff.md#weeks-per-month)
- The previous results are unexpected because none of the whole words in the returned `artist` fields begin with the matched string (`yster`). The `Ö` character in documents `_id: 0` and `_id: 1` is ignored when performing the match because `Ö` is a UTF-8 character. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#extend-regex-options-to-match-characters-outside-of-ascii)
- In this example, the $in array is truncated at the 376th element because the size of the command attribute would exceed maxLogSizeKB if it included the subsequent elements. The remainder of the command attribute is omitted. The truncated log entry resembles the following output: — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- mongos performs a broadcast operation for queries that do not include the shard key, routing queries to all shards in the cluster. Some queries that do include the shard key may still result in a broadcast operation depending on the distribution of data in the cluster and the selectivity of the query. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- With RBAC enforced, clients must specify a --username, --password, and --authenticationDatabase when connecting to the mongos in order to access cluster resources. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- In this example, the `$in` array is truncated at the 376th element because the size of the `command` attribute would exceed [`maxLogSizeKB`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.maxLogSizeKB) if it included the subsequent elements. The remainder of the `command` attribute is omitted. The truncated log entry resembles the following output: — [source](https://www.mongodb.com/docs/manual/reference/log-messages.md#truncation)
- - MongoDB Compass shows limited performance data when connected to a [`mongos`.](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) — [source](https://www.mongodb.com/docs/compass/performance.md#limitations)
- 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](https://www.mongodb.com/docs/atlas/tutorial/query-profiler.md#data-display-limitations)
- - 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#behavior)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#query-result-format)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#tailable-cursors)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.addOption.md#example)
- The `$eq` operator is equivalent to the `{ field: <value> }` form, except when `<value>` is a regular expression. See below for [examples.](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#std-label-eq-usage-examples) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#syntax)
- An explicit query that uses `$eq` and a regular expression only matches an object that is also a regular expression. The example query returns no results because values in the `company` field are strings. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#regex-match-behavior)
- The `$not` operator can yield unexpected results when used with an array. To match documents based on multiple false conditions, use [`$nor`.](https://www.mongodb.com/docs/manual/reference/operator/query/nor.md#mongodb-query-op.-nor) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#arrays)
- Some queries need to execute conditional logic when defining a query filter. The aggregation pipeline provides the [`$cond`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/cond.md#mongodb-expression-exp.-cond) operator to express conditional statements. By using `$expr` with the [`$cond`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/cond.md#mongodb-expression-exp.-cond) operator, you can specify a conditional filter for your query statement. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#use-expr-with-conditional-statements)
- Evaluates a boolean and returns the opposite boolean value; i.e. when passed an expression that evaluates to `true`, [`$not`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#mongodb-expression-exp.-not) returns `false`; when passed an expression that evaluates to `false`, [`$not`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#mongodb-expression-exp.-not) returns `true`. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#definition)
- The counter for `$expr` increments when the query runs. The counter for `$gt` does not. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- When comparing arrays, `$ne` behaves differently depending on whether you pass a scalar or an array as the comparison value. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#arrays)
- The `{ $ne : null }` filter on a dotted path can match a document even when `{ path : { $exists: true } }` does not, when the path traverses an array. For details, see [Null Comparisons on Array Fields.](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#std-label-null-semantics-arrays) — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#non-equality-filter)
- The previous query is invalid because it uses [`$ne`](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#mongodb-query-op.-ne) more than once on the `status` field at the same object level. Use [`$nin`](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#mongodb-query-op.-nin) instead: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/and.md#examples)
- Two similar comparisons are made in the [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage. First the [`$year`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/year.md#mongodb-expression-exp.-year) and [`$month`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/month.md#mongodb-expression-exp.-month) operators extract the year and month, respectively, from the `logoutTime` Date object. Then the month and year are checked to see if they match the selection targets. Since "January" is enc — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateSubtract.md#subtract-a-fixed-amount)
- | Option | Description | | --- | --- | | `i` | Case insensitivity to match upper and lower cases. For an example, see [Perform Case-Insensitive Regular Expression Match.](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#std-label-regex-case-insensitive) | | `m` | For patterns that include anchors (`^` for the start, `$` for the end), match at the beginning or end of each line for strings with multiline values. Without this option, these anchors match at beginning or end of the string. For an example, see [Multiline Match for Lines Starting with Specified Pattern.](https:// — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#syntax)
- When specifying `*UCP` or any other regular expression option, use the correct escape characters for your shell or driver. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#extend-regex-options-to-match-characters-outside-of-ascii)

## How-to and procedures

- To check if MongoDB must perform an in-memory sort, append [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) to the query and check the [explain results](https://www.mongodb.com/docs/manual/reference/explain-results.md#std-label-explain-results). If the query plan contains a `SORT` stage, then MongoDB must perform an in-memory sort operation. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#sort-and-index-use)
- To include a regular expression in an `$in` query predicate operator, you can only use JavaScript regular expression objects (`/pattern/` ). — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#in-expressions)
- To determine whether a query is a covered query, use the [`db.collection.explain()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain) or the [`explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) method. See [Covered Queries.](https://www.mongodb.com/docs/manual/reference/explain-results.md#std-label-explain-output-covered-queries) — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#explain-results)
- 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](https://www.mongodb.com/docs/manual/core/index-sparse.md#sparse-index-and-incomplete-results)
- To avoid an in-memory sort, place the range filter after the sort predicate. For more information on in-memory sorts, see cursor.allowDiskUse(). — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- To avoid an in-memory sort, place the range filter after the sort predicate. For more information on in-memory sorts, see [`cursor.allowDiskUse()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.allowdiskuse.md#mongodb-method-cursor.allowDiskUse) — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline.md#range)
- 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](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-only)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.readPref.md#specify-read-preference-tag-set)
- 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](https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency.md#cursor-snapshot)
- To index fields in embedded documents, use [dot notation](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-dot-notation). See [Create an Index on an Embedded Field.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-single/create-single-field-index.md#std-label-index-embedded-fields) — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#embedded-documents)
- Check for a blocking sort with explain(): a SORT stage in the plan means a blocking sort; no SORT stage means the index supplies the order. Use hint() when testing candidate indexes. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline/)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#override-readconcern)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#retrieve-distinct-values)
- 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](https://www.mongodb.com/docs/manual/core/query-plans.md#query-plan-and-cache-information)
- 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](https://www.mongodb.com/docs/manual/tutorial/measure-index-use.md#return-query-plan-with-explain)
- 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](https://www.mongodb.com/docs/manual/tutorial/measure-index-use.md#return-query-plan-with-explain)
- 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](https://www.mongodb.com/docs/manual/tutorial/measure-index-use.md#control-index-use-with-hint)
- To improve query performance for [time series collections](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-time-series-collection), add one or more [secondary indexes](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-secondary-index) to support common time series query patterns. Starting in MongoDB 6.3, MongoDB automatically creates a [compound index](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-compound.md#std-label-index-type-compound) on the `metaField` and `timeField` fields for new collections. — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#natural)
- To improve query performance, [create one or more secondary indexes](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#std-label-timeseries-add-secondary-index) on your `timeField` and `metaField` to support common query patterns. In versions 6.3 and higher, MongoDB creates a secondary index on the `timeField` and `metaField` automatically. — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-best-practices.md#create-secondary-indexes)
- To force MongoDB to use a particular index, use cursor.hint() (mongosh method) when testing indexes. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#create-indexes-with-collation)
- To learn how to use wildcard projection with a compound wildcard index to filter fields, see [Filter Fields with a `wildcardProjection`.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/index-wildcard-compound.md#std-label-wc-compound-index-wcProject) — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/create-wildcard-index-multiple-fields.md#learn-more)
- 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](https://www.mongodb.com/docs/manual/tutorial/analyze-query-plan.md#mongodb-shell)
- 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](https://www.mongodb.com/docs/manual/tutorial/analyze-query-plan.md#mongodb-shell)
- 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](https://www.mongodb.com/docs/manual/tutorial/analyze-query-plan.md#mongodb-shell)
- To determine whether a pipeline uses indexes, review the query plan and look for `IXSCAN` or `DISTINCT_SCAN` plans. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#indexes)
- To achieve a covered query, you must index projected fields. The ESR (Equality, Sort, Range) rule applies to the order of fields in the index. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- To determine whether a query is a covered query, use the db.collection.explain() or the explain() method. See Covered Queries. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- To achieve a covered query, you must index projected fields. The [ESR (Equality, Sort, Range) rule](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline.md#std-label-esr-indexing-guideline) applies to the order of fields in the index. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#example)
- 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](https://www.mongodb.com/docs/manual/core/index-sparse.md#sparse-index-on-a-collection-cannot-return-complete-results)
- Use a Sparse Index to Improve $exists Performance — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists/)
- To analyze query performance, see [Interpret Explain Plan Results.](https://www.mongodb.com/docs/manual/tutorial/analyze-query-plan.md) — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#create-indexes-to-support-queries)
- To view the MongoDB 8.0 `queryShapeHash` and `planCacheShapeHash` hexadecimal strings, you can use the [`explain`](https://www.mongodb.com/docs/manual/reference/command/explain.md#mongodb-dbcommand-dbcmd.explain) command. — [source](https://www.mongodb.com/docs/manual/core/query-shapes.md#matching-query-shapes)
- To include [expressions](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) in a query predicate, use the [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) operator. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#expressions-in-query-predicates)
- To count the number of documents in the `movies` collection, use the following operation: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#count-all-documents-in-a-collection)
- To resolve, remove the component of the field path that follows the [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) projection operator. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#positional-operator-placement-restriction)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#sort-consistency)
- 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](https://www.mongodb.com/docs/compass/schema.md#query-builder)
- To see full aggregation examples that use the [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) stage, see the [Complete Aggregation Pipeline Tutorials.](https://www.mongodb.com/docs/manual/tutorial/aggregation-complete-examples.md#std-label-aggregation-complete-examples) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#learn-more)
- To perform an `$elemMatch` projection when using the .NET/C# driver, call the `ElemMatch()` method on the projection builder. Pass the name of the array field to project and the filter to apply to the array elements. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#zipcode-search)
- To match scalar values, use the equality operator along with the scalar value that you want to match (`{$eq: <scalar value>}`). For example, the following [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) operation queries for all documents where the value of the `zipcode` field is `"63109"`. The projection includes the matching element of the `athletics` array where the value is `basketball`: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- To perform an `$elemMatch` operation against scalar values in an array when using the .NET/C# driver, call the `ElemMatch()` method on the projection builder. Pass the name of the array field to project and an equality filter for the field `"$eq"` and the value you want to compare against. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- 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](https://www.mongodb.com/docs/manual/reference/command/getMore.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#authentication-parameters)
- To enable log redaction on a running `mongod` or `mongos`, use the following command: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#logging-parameters)
- To avoid this, users should connect to single-shard clusters through a router, like `mongos`. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- To make this setting persistent, set `activeFaultDurationSecs` in your [mongos config file](https://www.mongodb.com/docs/manual/reference/configuration-options.md#std-label-configuration-options) using the [`setParameter`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-setParameter) option as in the following example: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#health-manager-parameters)
- To make this setting persistent, set `healthMonitoringIntensities` in your [mongos config file](https://www.mongodb.com/docs/manual/reference/configuration-options.md#std-label-configuration-options) using the [`setParameter`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-setParameter) option as in the following example: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#intensity-levels)
- To make this setting persistent, set `healthMonitoringIntervals` in your [mongos config file](https://www.mongodb.com/docs/manual/reference/configuration-options.md#std-label-configuration-options) using the [`setParameter`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-setParameter) option as in the following example: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#health-managers)
- To make this setting persistent, set `progressMonitor` in your [mongos config file](https://www.mongodb.com/docs/manual/reference/configuration-options.md#std-label-configuration-options) using the [`setParameter`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-setParameter) option as in the following example: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#progressmonitor-fields)
- To include the text search score by using the .NET/C# driver, call the [MetaTextScore()](https://mongodb.github.io/mongo-csharp-driver/3.11.0/api/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.MetaTextScore.html) method on the projection builder. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#meta-indexkey)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#about-this-task)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/changeStream.md#mongodb-shell)
- To open the cursor, run `cur`. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/changeStream.md#mongodb-shell)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- Ensure [`--clusterIpSourceAllowlist`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--clusterIpSourceAllowlist) includes the IP address *or* CIDR ranges that include the IP address of each replica set member or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) in the deployment to ensure healthy communication between cluster components. — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#core-options)
- To check the lock status of the database, connect to a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance using [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh). Issue the following command sequence to switch to the `config` database and display all outstanding locks on the shard database: — [source](https://www.mongodb.com/docs/manual/administration/monitoring.md#stale-locks)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#cursor-handling)
- To manually iterate over the results, assign the returned cursor to a variable with the `var` keyword, as shown in the following sections. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#iterate-the-returned-cursor)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#query-a-time-series-collection)
- To return one document from a time series collection, you can use the `findOne()` method. The following example uses the `projection` field in the query to omit the `_id` field from the returned documents: — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#query-a-time-series-collection)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#query-a-time-series-collection)
- To return one document from a time series collection, you can use the [`db.collection.findOne()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.findone.md#mongodb-method-db.collection.findOne) method. The following example uses the `projection` field in the query to omit the `_id` field from the returned documents: — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#query-a-time-series-collection)
- To specify a projection document, chain the [com.mongodb.client.FindIterable.projection](https://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/client/FindIterable.html#projection-org.bson.conversions.Bson-) method to the `find` method. The example uses the [com.mongodb.client.model.Projections](http://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/client/model/Projections.html) class to create the projection documents. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- To specify an initial batch size for the cursor, use the following syntax for the `cursor` option: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#specify-an-initial-batch-size)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#specify-an-initial-batch-size)
- 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](https://www.mongodb.com/docs/compass/query/maxtimems.md#learn-more)
- To find documents where `status` is either `new` or `processing`, use [`$in`:](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#mongodb-query-op.-in) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/and.md#examples)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.disableBlockWarnings.md#definition)
- To detect if the MongoDB instance that your client is connected to is mongos, use the hello command. When a client connects to a mongos, hello returns a document with a msg field that holds the string isdbgrid. For example: — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Use Self-Managed Internal/Membership Authentication to enforce intra-cluster security and prevent unauthorized cluster components from accessing the cluster. You must start each mongod or mongos in the cluster with the appropriate security settings in order to enforce internal authentication. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Avoid overloading the connection resources of a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance by adjusting the connection pool size to suit your use case. Start at 110-115% of the typical number of current database requests, and modify the connection pool size as needed. Refer to the [Connection Pool Options](https://www.mongodb.com/docs/manual/reference/connection-string-options.md#std-label-connection-pool-options) for adjus — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#manage-connection-pool-sizes)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/changeStreamSplitLargeEvent.md#mongodb-shell)
- To achieve an even data distribution across all shards in the cluster, a balancer runs in the background to migrate ranges across the shards. — [source](https://www.mongodb.com/docs/manual/sharding/)
- to a shard. Please connect to the cluster via a router (mongos)." — [source](https://www.mongodb.com/docs/manual/sharding/)
- To run a non-supported database command directly against a node in a sharded cluster, you must either connect to mongos or have the maintenance-only directShardOperations role. — [source](https://www.mongodb.com/docs/manual/sharding/)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#change-stream-with-full-document-update-lookup)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#query-result-format)
- Create a cursor variable named `sensorCursor` that reads the documents from the `sensor` collection: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#examples)
- To perform a case-insensitive regex pattern matching, use the [`i` Option](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexmatch.md#std-label-regexMatch-example-i-options) instead. See [`i` Option](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexmatch.md#std-label-regexMatch-example-i-options) for an example. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexMatch.md#regexmatch-and-collation)
- Use the `$not` operator with another operator expression. To use `$not` for an inequality check, use: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#syntax)
- To specify an [`$exists`](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#mongodb-query-op.-exists) expression, use the following prototype: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#syntax)
- Use the [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. The [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) provides greater flexibility, but requires that the database processes the JavaScript expression or function for *each* document in the collection. Reference the document in the JavaScript expression or function using either `this` or `obj` . — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#definition)
- To filter results using a variable in a pipeline [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage, you must access the variable within the [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) operator. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#use-variables-in-let)
- To query for fields that **exist** and are **not null**, use the `{ $ne : null }` filter. — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#non-equality-filter)
- To use `$regex` with [`mongodump`](https://www.mongodb.com/docs/database-tools/mongodump.md#mongodb-binary-bin.mongodump), enclose the query document in single quotes ('\{ ... }') to ensure it doesn't interact with the shell. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#syntax)
- To include a regular expression in a comma-separated list of query conditions for the field, use the `$regex` operator. For example: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#implicit-and-conditions-for-the-field)
- To use either the `x` option or `s` options, you must use the `$regex` operator expression *with* the [`$options`](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#mongodb-query-op.-options) operator. For example, to specify the `i` and the `s` options, you must use [`$options`](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#mongodb-query-op.-options) for both: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#x-and-s-options)
- To use PCRE (Perl Compatible Regular Expressions)-supported features in a regular expression that aren't supported in JavaScript, use the `$regex` operator and specify the pattern as a string. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#pcre-versus-javascript)

## Examples and snippets

- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/find.md#syntax)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#use-in-with-a-regular-expression)
- ```javascript — `metrics : {` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- ```javascript — `db.collection.find( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#index-use)
- ```javascript — `db.runCommand( {` … — [source](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#use-variables-in-let)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#perform-a-concise-correlated-subquery-with-lookup)
- ```javascript — `db.movies.countDocuments( { metacritic: { $ne: null } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- ```javascript — `uri : 'statistics:',` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#wiredtiger)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/find.md#specify-a-sort-and-limit)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-projection-and-sort)
- ```javascript — `_id: {` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- ```python — `cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "instock.qty": 1})` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#projection-on-embedded-documents-in-an-array)
- ```javascript — `const cursor = db` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#projection-on-embedded-documents-in-an-array)
- ```javascript — `_id: 0,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter.md#filter-based-on-regular-expression-match)
- ```javascript — `db.getSiblingDB("admin").aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#mongos-composite-view-output)
- ```javascript — `cakeSalesCursor = db.cakeSales.watch( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- ```javascript — `{ name: { $in: [ /^acme/i, /^ack/ ] } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#in-expressions)
- ```text — `plot: 'Aliens come to Earth seeking scientists to help them in their war.',` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#use-in-with-a-regular-expression)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/count.md#override-default-read-concern)
- ```javascript — `db.restaurants.find( { _id: 5 } ).readConcern("linearizable").maxTimeMS(10000)` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.readConcern.md#linearizable-read-concern-performance)
- ```javascript — `db.movies.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#override-readconcern)
- ```c — `/* Make a new session, session2, and make it causally-consistent` … — [source](https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency.md#examples)
- ```javascript — `db.collection.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/command/count.md#accuracy-and-sharded-clusters)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#example)
- ```javascript — `db.movies.find( { year: { $in: [1903, 1909] } },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/or.md#or-compared-to-in)
- ```shell — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#examples)
- ```javascript — `db.collection.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.maxAwaitTimeMS.md#definition)
- ```javascript — `db.sales.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.maxAwaitTimeMS.md#example)
- ```javascript — `"ns" : <string>,` … — [source](https://www.mongodb.com/docs/manual/reference/command/collStats.md#output)
- ```javascript — `db.theaters.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/map.md#add-to-each-element-of-an-array)
- ```javascript — `db.theaters.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/map.md#truncate-each-array-element)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/maxN-array-element.md#example)
- ```javascript — `db.collection.findOneAndUpdate(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#syntax)
- ```json — `"_id" : ObjectId("<object-id>"),` … — [source](https://www.mongodb.com/docs/atlas/data-federation/query/view-query-history.md#retrieve-details-about-the-queries)
- ```python — `cursor = db.inventory.find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```javascript — `const cursor = db` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```javascript — `const cursor = db` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```php — `$cursor = $db->inventory->find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- ```php — `$cursor = $db->inventory->find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```php — `$cursor = $db->inventory->find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- ```php — `$cursor = $db->inventory->find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- ```php — `$cursor = $db->inventory->find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- ```php — `$cursor = $db->inventory->find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#projection-on-embedded-documents-in-an-array)
- ```php — `$cursor = $db->inventory->find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```javascript — `"op" : "command",` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#specify-a-comment)
- ```none — `db.collection.findOneAndDelete(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndDelete.md#syntax)
- ```javascript — `db.collection.findOneAndReplace(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndReplace.md#syntax)
- ```javascript — `db.runCommand( {` … — [source](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#aggregate-data-with-multi-stage-pipeline)
- ```javascript — `db.newDailyCommentCount.createIndex(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#create-a-new-collection-if-output-collection-is-non-existent)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-variables-defined-in-the-merge-stage)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-variables-defined-in-the-aggregate-command)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-variables-defined-in-the-merge-stage-and-aggregate-command)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind.md#group-by-unwound-values)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind.md#unwind-multiple-array-fields)
- ```javascript — `db.collection.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md#definition)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#use-lookup-with-an-array)
- ```javascript — `db.users.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#perform-an-uncorrelated-subquery-with-lookup)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#suppress-id-field-in-the-output-documents)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#conditionally-exclude-fields)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#match-values)
- ```javascript — `db.people.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter.md#access-the-index-of-each-item-in-an-array)
- ```javascript — `db.people.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter.md#use-idx-to-access-the-index)
- ```javascript — `db.places.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear.md#specify-which-geospatial-index-to-use)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/count.md#specify-the-index-to-use)
- ```javascript — `ok: 1,` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.stats.md#statistics-lookup-with-index-details)
- ```javascript — `ok: 1,` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.stats.md#statistics-lookup-with-filtered-index-details)
- ```text — `"explainVersion": "1",` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#last-point-queries-on-time-series-collections)
- ```java — `var explainCommand = new Document("explain", new Document()` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#use-secondary-indexes-to-improve-sort-performance)
- ```javascript — `{ metadata.type:{ $in: ["temperature", "pressure"] }}` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#create-2dsphere-indexes)
- ```javascript — `const filter = { 'metadata.type': { $in: ['temperature', 'pressure'] } };` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#use-secondary-indexes-to-improve-sort-performance)
- ```javascript — `const explainResult = await database.command({` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#use-secondary-indexes-to-improve-sort-performance)
- ```python — `filter_query = {"metadata.type": {"$in": ["temperature", "pressure"]}}` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#use-secondary-indexes-to-improve-sort-performance)
- ```python — `explain_result = database.command(` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#use-secondary-indexes-to-improve-sort-performance)
- ```javascript — `db.products.find( { _id: { $in: [ 6, 7 ] } } ).min( { price: Decimal128("1.39") } ).hint( { price: 1 } )` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#interaction-with-index-selection)
- ```javascript — `db.collection.find( { a: 5, b: 5 } ).count()` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#index-use)
- ```javascript — `db.orders.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#specify-the-index-to-use)
- ```javascript — `db.movies.countDocuments( {}, { hint: { rated: 1 } } )` … — [source](https://www.mongodb.com/docs/manual/core/index-sparse.md#sparse-index-and-incomplete-results)
- ```javascript — `db.movies.countDocuments()` … — [source](https://www.mongodb.com/docs/manual/core/index-sparse.md#sparse-index-and-incomplete-results)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#sort-by-an-array-field)
- ```javascript — `db.companies.find( { company: /MongoDB/ }, {_id: 0 })` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#regex-match-behavior)
- ```javascript — `// Groups per client, user, and namespace; counts active/inactive` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#count-collection-connections)
- ```javascript — `const db = client.db("admin");` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#inactive-sessions)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#compare-two-fields-from-a-single-document)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#use-expr-with-conditional-statements)
- ```javascript — `db.inventory.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/ne.md#example)
- ```javascript — `db.cakeFlavors.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#use-variables-in-let-option)
- ```javascript — `db.movies.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#use-variables-in-let)
- ```javascript — `db.currentOp(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.currentOp.md#write-operations-waiting-for-a-lock)
- ```shell — `db.movies.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bottomN.md#set-n-dynamically-based-on-the-group-key)
- ```javascript — `db.connectionTime.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateSubtract.md#filter-by-relative-dates)
- ```javascript — `db.voters.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rand.md#select-random-items-from-a-collection)
- ```javascript — `db.adminCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/currentOp.md#write-operations-waiting-for-a-lock)
- ```javascript — `db.shipping.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateAdd.md#filter-on-a-date-range)
- ```javascript — `db.movies.findOne(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne.md#use-variables-in-let-option)
- ```javascript — `db.users.createIndex(` … — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#comparison-with-sparse-indexes)
- ```javascript — `db.users.find( { name: "Ned Stark", email: { $regex: /gameofthron\.es$/ } } )` … — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#comparison-with-sparse-indexes)
- ```javascript — `db.users.find( { name: "Ned Stark", email: { $exists: false } } )` … — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#comparison-with-sparse-indexes)
- ```javascript — `db.users.createIndex(` … — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#partial-index-with-unique-constraint)
- ```text — `{ "countries.0": { $ne: "USA" } }` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-for-an-element-by-the-array-index-position)
- ```javascript — `"query" : { "qty" : { "$gt" : 10 } },` … — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheClear.md#clear-cached-plans-for-a-plan-cache-query-shape)
- ```javascript — `db.users.find( { password: { $exists: true } } ).sort({ password: 1 }).limit(5)` … — [source](https://www.mongodb.com/docs/manual/core/index-sparse.md#create-a-sparse-index-on-a-collection)
- ```javascript — `"type" : "idleSession",` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#mongos-composite-view-output)
- ```javascript — `"shard" : "shardB",` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#mongos-per-shard-output)
- ```swift — `let options = ClientSessionOptions(causalConsistency: true)` … — [source](https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency.md#examples)
- ```javascript — `db.inventory.find( { $ne : [ "product_attributes.tags", null ] } )` … — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#array-field-is-not-equal-to-null)
- ```javascript — `db.inventory.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#equality-matches-on-documents-and-arrays)
- ```javascript — `db.inventory.find(` … — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#field-does-not-exist)
- ```csharp — `// Indexes on ``timeField`` descending are more performant because they` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#last-point-queries-on-time-series-collections)
- ```java — `// Indexes on ``timeField`` descending are more performant because they` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#last-point-queries-on-time-series-collections)
- ```javascript — `// Indexes on ``timeField`` descending are more performant because they` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#last-point-queries-on-time-series-collections)
- ```python — `# Indexes on ``timeField`` descending are more performant because they` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#last-point-queries-on-time-series-collections)
- ```javascript — `{ $substrCP: [ <string expression>, <code point index>, <code point count> ] }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/substrCP.md#definition)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#syntax)
- ```javascript — `db.movies.explain().count( { year: { $gt: 2000 } } )` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#queryplanner-mode)
- ```javascript — `var cursor = db.users.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#explain-with-options)
- ```javascript — `{ _id: 0, index: -1 },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/indexOfArray.md#example)
- ```javascript — `"query" : { "status" : "A" },` … — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheClearFilters.md#clear-specific-index-filter-on-collection)
- ```php — `$s2 = $client->startSession(` … — [source](https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency.md#examples)
- ````text — `## Summary` … — [source](https://www.mongodb.com/docs/compass/query-with-natural-language/compass-ai-assistant.md#explain-plan)
- [ — `{ "$match": { "borough": "Manhattan", "cuisine": "Italian" } },` … — [source](https://www.mongodb.com/docs/compass/query-with-natural-language/compass-ai-assistant.md#explain-plan)
- ```javascript — `"t":{"$date":"2026-08-14T13:36:19.194-04:00"},"s":"D1",` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/toggle-logging.md#querystats-output-included)
- ```none — `"filters" : [` … — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheListFilters.md#output)
- ```javascript — `{ $substrBytes: [ <string expression>, <byte index>, <byte count> ] }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/substrBytes.md#definition)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/explain.md#queryplanner-mode)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/explain.md#executionstats-mode)
- ```javascript — `db.adminCommand( {` … — [source](https://www.mongodb.com/docs/manual/reference/command/setQuerySettings.md#set-query-settings-by-passing-in-a-query-shape-hash)
- ```javascript — `db.getSiblingDB("admin").aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.currentOp.md#active-indexing-operations)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-only)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-and-collation)
- ```javascript — `db.pizzaOrders.explain().find(` … — [source](https://www.mongodb.com/docs/manual/core/query-shapes.md#matching-query-shapes)
- ```javascript — `db.pizzaOrders.explain().find(` … — [source](https://www.mongodb.com/docs/manual/core/query-shapes.md#different-query-shape)
- ```javascript — `"t":{` … — [source](https://www.mongodb.com/docs/manual/reference/log-messages.md#slow-operation)
- ```javascript — `function printStudents(pageNumber, nPerPage) {` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#using-skip)
- ```javascript — `function printStudents(startValue, nPerPage) {` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#descending-order)
- ```javascript — `function printStudents(startValue, nPerPage) {` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#ascending-order)
- ```javascript&#xA;:copyable:false — `"desc" : "query analyzer",` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#sharded-cluster-mongos-query-analyzer-output)
- ```javascript — `"_id": { "client": "192.0.2.10", "user": ["appUser"], "ns": "db1.collA" },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#count-collection-connections)
- ```shell — `_id: 1,` … — [source](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#save-a-cursor-with-let)
- ```javascript — `"$sort" : {` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#sort-limit-coalescence)
- ```javascript — `db.bios.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#use-aggregation-expression)
- ```javascript — `{ "birth" : ISODate("1924-12-03T05:00:00Z"), "contribs" : [ "Fortran", "ALGOL", "Backus-Naur Form", "FP" ], "n` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#use-aggregation-expression)
- ```javascript — `db.inventory.find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- ```javascript — `item: 'journal',` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- ```javascript — `{ "item": "journal", "status": "A", "size": { "h": 14, "w": 21, "uom": "cm" }, "instock": [ { "warehouse": "A"` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- ```javascript — `db.users.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#allowdiskuse-with-options)
- ```javascript — `db.sensors.find({"sensor-location" : "Unit 12"}).` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse.md#example)
- ```javascript — `db.sales.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter.md#filter-based-on-regular-expression-match)
- ```javascript — `{ title: 'Band of Brothers', imdb: { rating: 9.6, votes: 183802 } },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#use-expr-with-conditional-statements)
- ```javascript — `title: 'Winsor McCay, the Famous Cartoonist of the N.Y. Herald and His Moving Comics',` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#exists-false)
- ```javascript — `{ _id: 100, sku: 'abc123', description: 'Single line description.' },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#perform-case-insensitive-regular-expression-match)
- ```JSON — `"_id": { "$oid":"<object-id>" },` … — [source](https://www.mongodb.com/docs/atlas/atlas-ui/query/filter.md#match-by-exclusion-not)
- ```javascript — `_id: 0,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter.md#filter-based-on-number-comparison)
- ```javascript — `_id: 0,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter.md#use-the-limit-field)
- ```javascript — `_id: 0,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter.md#filter-based-on-string-equality-match)
- ```javascript — `db.flowers.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setDifference.md#example)
- ```javascript — `db.movies.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#count-the-number-of-documents-in-a-collection)
- ```javascript — `_id: null,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#count-the-number-of-documents-in-a-collection)
- ```sql — `SELECT COUNT(*) AS count FROM movies` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#count-the-number-of-documents-in-a-collection)
- ```javascript — `{ _id: 1909, totalRuntime: 14, averageRuntime: 14, count: 1 },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-year)
- ```sql — `SELECT year,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-year)
- ```javascript — `db.movies.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-null)
- ```javascript — `_id: null,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-null)
- ```sql — `SELECT Sum(runtime) AS totalRuntime,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-null)
- ```javascript — `db.collection.countDocuments( <query>, <options> )` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#syntax)
- ```javascript — `db.deliveries.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/isoWeek.md#example)
- ```javascript — `db.inventory.find( { "instock.qty": { $gt: 25 } }, { "instock.$": { $slice: 1 } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#positional-operator-and-slice-restriction)
- ```javascript — `db.runCommand( { count: 'orders' } )` … — [source](https://www.mongodb.com/docs/manual/reference/command/count.md#count-all-documents)
- ```javascript — `db.runCommand( { count:'orders',` … — [source](https://www.mongodb.com/docs/manual/reference/command/count.md#count-documents-that-match-a-query)
- ```javascript — `db.runCommand( { count:'orders',` … — [source](https://www.mongodb.com/docs/manual/reference/command/count.md#skip-documents-in-count)
- ```javascript — `db.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/hash.md#hash-a-literal-string)
- ```javascript — `{ $in: [ <expression>, <array expression> ] }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#definition)
- ```javascript — `db.getSiblingDB("sample_restaurants").restaurants.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#sort-consistency)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#ascending-descending-sort)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#filter-and-sort-by-an-array-field)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#examples)
- ```python — `cursor = db.inventory.find({"item": "canvas"})` … — [source](https://www.mongodb.com/docs/manual/tutorial/insert-documents.md#insert-a-single-document)
- ```javascript — `db.collection.find(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#syntax)
- ```javascript — `db.inventory.find( { }, { qty: 1, "details.colors": { $slice: 1 } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#slice-of-embedded-array)
- ```javascript — `db.inventory.find( { }, { _id: 0, "details.colors": { $slice: 1 } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#slice-of-embedded-array)
- ```javascript — `db.posts.find( {}, { comments: { $slice: 3 } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#return-an-array-with-its-first-3-elements)
- ```javascript — `db.posts.find( {}, { comments: { $slice: -3 } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#return-an-array-with-its-last-3-elements)
- ```javascript — `db.posts.find( {}, { comments: { $slice: [ 1, 3 ] } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#return-an-array-with-3-elements-after-skipping-the-first-element)
- ```javascript — `db.posts.find( {}, { comments: { $slice: [ -1, 3 ] } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#return-an-array-with-3-elements-after-skipping-the-last-element)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#covered-queries)
- ```javascript — `db.adminCommand( {` … — [source](https://www.mongodb.com/docs/manual/reference/command/setQuerySettings.md#set-query-settings-by-passing-in-a-query)
- ```javascript — `_id: 1,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphLookup.md#across-multiple-collections)
- ```javascript — `use sample_mflix` … — [source](https://www.mongodb.com/docs/mongodb-shell/crud/read.md#specify-conditions-using-query-operators)
- ```javascript — `db.createView(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/createObjectId.md#generate-identifiers-in-a-view)
- ```javascript — `db.collection.find( { company: "MongoDB" }, {_id: 0 })` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#regex-match-behavior)
- ```javascript — `db.companies.find( { company: { $eq: /MongoDB/ } }, {_id: 0 } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#regex-match-behavior)
- ```javascript — `const db = client.db("admin");` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#sampled-queries)
- ```javascript — `"command" : {` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- ```javascript — `db.jsonStrings.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toObject.md#convert-string-to-object)
- ```javascript — `ok: 1,` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.stats.md#basic-stats-lookup)
- ```javascript — `ok: 1,` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.stats.md#stats-lookup-with-scale)
- ```javascript — `{ $skip: <positive 64-bit integer> }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#definition)
- ```javascript — `db.article.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-shell)
- ```javascript — `{ $count: <string> }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#syntax)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#mongodb-shell)
- ```javascript — `$collStats:` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#definition)
- ```javascript — `{ "ns" : "test.matrices",` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#latencystats)
- ```javascript — `localTime : 2020-03-06T01:44:57.437Z,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#storagestats)
- ```javascript — `db.matrices.aggregate( [ { $collStats: { count: { } } } ] )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#count)
- ```javascript — `"ns" : "test.matrices",` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#count)
- ```javascript — `"ns" : "test.matrices",` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#collstats-on-sharded-collections)
- ```csharp — `var results = schoolsCollection` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#zipcode-search)
- ```csharp — `var results = schoolsCollection` … — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/getMore.md#syntax)
- ```javascript — `"cursor" : {` … — [source](https://www.mongodb.com/docs/manual/reference/command/getMore.md#output)
- ```javascript — `db.collection.find({...}).collation({...}).sort({...});` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.collation.md#examples)
- ```javascript — `_id: 0,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateTrunc.md#truncate-order-dates-in-a-project-pipeline-stage)
- ```none — `{ $count: { } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#syntax)
- ```javascript — `db.stockSales.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#obtain-the-incrementing-ordinal-from-a-timestamp-field)
- ```bash — `mongod --setParameter cursorTimeoutMillis=300000` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- ```javascript — `db.adminCommand( { setParameter: 1, cursorTimeoutMillis: 300000 } )` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- ```bash — `mongos --setParameter globalConnPoolIdleTimeoutMinutes=10` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- ```bash — `mongos --setParameter httpVerboseLogging=true` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- ```bash — `mongod --setParameter abortStreamingHelloWithSmallTimeout=true` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- ```bash — `mongod --setParameter minWaitForStreamingHelloMillis=1000` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- ```bash — `mongod --setParameter enableFinerGrainedCatalogCacheRefresh=true` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter findShardsOnConfigTimeoutMS=30000` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter mongosShutdownTimeoutMillisForSignaledShutdown=250` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter queryAnalysisSamplerConfigurationRefreshSecs=60` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter ShardingTaskExecutorPoolHostTimeoutMS=120000` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter ShardingTaskExecutorPoolMaxConnecting=20` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter ShardingTaskExecutorPoolMaxSize=20` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter ShardingTaskExecutorPoolMaxQueueDepth=10` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter ShardingTaskExecutorPoolMaxSizeForConfigServers=2` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter ShardingTaskExecutorPoolMinSize=2` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter ShardingTaskExecutorPoolMinSizeForConfigServers=2` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter ShardingTaskExecutorPoolRefreshRequirementMS=90000` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter ShardingTaskExecutorPoolRefreshTimeoutMS=30000` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter taskExecutorPoolSize=6` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- ```bash — `mongos --setParameter activeFaultDurationSecs=300` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#health-manager-parameters)
- ```bash — `mongos --setParameter 'healthMonitoringIntensities={ values:[ { type:"dns", intensity: "critical"} ] }'` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#intensity-levels)
- ```bash — `mongos --setParameter 'healthMonitoringIntervals={ values:[ { type:"ldap", interval: "30000"} ] }'` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#health-managers)
- ```bash — `mongos --setParameter 'progressMonitor={"interval": 1000, "deadline": 300}'` … — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#progressmonitor-fields)
- ```none — `_id: <uuid>,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listSampledQueries.md#read-queries)
- ```javascript — `ns: 'sample_mflix.nonExistentCollection',` … — [source](https://www.mongodb.com/docs/manual/reference/command/collStats.md#example)
- ```javascript — `db.article.aggregate(` … — [source](https://www.mongodb.com/docs/compass/query/limit.md#how-does-the-compass-query-compare-to-mongodb-and-sql-queries)
- ```javascript — `$limit : 10` … — [source](https://www.mongodb.com/docs/compass/query/limit.md#how-does-the-compass-query-compare-to-mongodb-and-sql-queries)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/facet.md#mongodb-shell)
- ```javascript — `categorizedByGenres: [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/facet.md#mongodb-shell)
- ```javascript — `db.engineers.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortArray.md#sort-on-a-field)
- ```javascript — `db.engineers.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortArray.md#sort-on-a-subfield)
- ```javascript — `db.engineers.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortArray.md#sort-on-multiple-fields)
- ```javascript — `db.engineers.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortArray.md#sort-an-array-of-integers)
- ```javascript — `db.engineers.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortArray.md#sort-on-mixed-type-fields)
- ```text — `cursor: {` … — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/fundamentals/keys-key-vaults.md#key-vault-collections)
- ```javascript — `{ "_id" : 0.75, "count" : 1 }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#meta-textscore)
- ```csharp — `var filter = Builders<Movie>.Filter.Text("future");` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#meta-indexkey)
- ```javascript — `db.users.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-shell)
- ```javascript — `db.createView( "movieComments", "movies", [` … — [source](https://www.mongodb.com/docs/manual/core/views/join-collections-with-view.md#create-a-joined-view)
- ```javascript — `db.movieComments.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/core/views/join-collections-with-view.md#query-the-view)
- ```javascript — `db.bakeryOrders.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setEquals.md#example)
- ```javascript — `_id: 4,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setWindowFields.md#use-documents-window-to-obtain-cumulative-quantity-for-each-state)
- ```javascript — `_id: 5,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setWindowFields.md#use-documents-window-to-obtain-cumulative-quantity-for-each-year)
- ```javascript — `_id: 5,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setWindowFields.md#use-documents-window-to-obtain-moving-average-quantity-for-each-year)
- ```javascript — `_id: 5,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setWindowFields.md#use-documents-window-to-obtain-cumulative-and-maximum-quantity-for-each-year)
- ```javascript — `_id: 2,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setWindowFields.md#range-window-example)
- ```javascript — `_id: 4,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setWindowFields.md#use-a-time-range-window-with-a-positive-upper-bound)
- ```javascript — `_id: 4,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setWindowFields.md#use-a-time-range-window-with-a-negative-upper-bound)
- ```javascript — `_id: 0,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setWindowFields.md#comparison-with-previous-values-example)
- ```javascript — `db.collection.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sampleRate.md#examples)
- ```javascript — `{ $sort: { age : -1 } },` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#project-unset-skip-sequence-optimization)
- ```javascript — `{ $sort : { age : -1 } },` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#sort-limit-coalescence)
- ```javascript — `{ $limit: 100 },` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#limit-limit-coalescence)
- ```javascript — `{ $skip: 5 },` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#skip-skip-coalescence)
- ```javascript — `{ $skip: 7 }` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#skip-skip-coalescence)
- ```javascript — `{ $sort: { age : -1 } },` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#sort-skip-limit-sequence)
- ```javascript — `"$sort" : {` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#sort-skip-limit-sequence)
- ```javascript — `db.grades.findOneAndUpdate(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#project-the-returned-document)
- ```javascript — `try {` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#update-document-with-time-limit)
- ```json — `indexBulkBuilder: {` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#indexbulkbuilder)
- ```json — `indexStats: {` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#indexstats)
- ```javascript — `host : <string>,` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#instance-information)
- ```javascript — `opcounters : {` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#opcounters)
- ```javascript — `opcountersRepl : {` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#opcountersrepl)
- ```javascript — `querySettings: {` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#querysettings)
- ```javascript — `spillWiredTiger: {` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#spillwiredtiger)
- ```bash — `var session = db.getMongo().startSession()` … — [source](https://www.mongodb.com/docs/manual/reference/limits.md#sessions)
- ```json — `"cursor": {` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-automatic-removal.md#retrieve-the-current-value-of-expireafterseconds)
- ```javascript — `cursor: {` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-automatic-removal.md#retrieve-the-current-value-of-expireafterseconds)
- ```javascript — `{ _id: { min: 2, max: 5 }, count: 1 },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/documents.md#test-a-pipeline-stage)
- ```javascript — `db.collection.find( <query>, <projection>, <options> )` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#syntax)
- ```javascript — `db.users.find(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#limit-with-options)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/concatArrays.md#example)
- ```javascript — `db.inventory.find().batchSize(10)` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md#example)
- ```javascript — `{ $group: { _id: <expression>, count: { $sum: 1 } } },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortByCount.md#behavior)
- ```javascript — `{ _id: "painting", count: 6 },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortByCount.md#mongodb-shell)
- ```javascript — `db.movies.find( { title: "The Godfather", metacritic: 100 }, { _id: 0, title: 1 } )` … — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-compound/create-compound-index.md#results)
- ```javascript — `db.movies.find( { title: "The Godfather" }, { _id: 0, title: 1 } )` … — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-compound/create-compound-index.md#results)
- ```csharp — `var query =` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#query-a-time-series-collection)
- ```java — `Date target = Date.from(Instant.parse("2045-11-19T18:00:00Z"));` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#query-a-time-series-collection)
- ```javascript — `const result = await weather.findOne(` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#query-a-time-series-collection)
- ```javascript — `db.weather.findOne(` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#query-a-time-series-collection)
- ```javascript — `const pipeline = [` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- ```javascript — `for await (const document of cursor) {` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- ```python — `pipeline = [` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- ```python — `for doc in cursor:` … — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- ```javascript — `{ _id: 0, result: 127 },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bitXor.md#example)
- ```javascript — `cursor.comment( <string> )` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.comment.md#definition)
- ```javascript — `db.artists.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#bucket-by-year-and-filter-by-bucket-results)
- ```javascript — `{ "_id" : 1840, "count" : 1, "artists" : [ { "name" : "Odilon Redon", "year_born" : 1840 } ] }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#bucket-by-year-and-filter-by-bucket-results)
- ```javascript — `{ "_id" : 1860, "count" : 4, "artists" :` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#bucket-by-year-and-filter-by-bucket-results)
- ```javascript — `db.artwork.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#use-bucket-with-facet-to-bucket-by-multiple-fields)
- ```javascript — `"price" : [ // Output of first facet` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#use-bucket-with-facet-to-bucket-by-multiple-fields)
- ```javascript — `db.distances.aggregate([{` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/range.md#example)
- ```javascript — `// Ascending sort` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#sort-by-an-array-field)
- ```javascript — `// Descending sort` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#sort-by-an-array-field)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#filter-and-sort-by-an-array-field)
- ```javascript — `db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```python — `cursor = db.inventory.find({"status": "A"})` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-fields-in-matching-documents)
- ```python — `cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1})` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- ```python — `cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "_id": 0})` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```python — `cursor = db.inventory.find({"status": "A"}, {"status": 0, "instock": 0})` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- ```python — `cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "size.uom": 1})` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- ```python — `cursor = db.inventory.find({"status": "A"}, {"size.uom": 0})` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- ```java — `findIterable = collection.find(eq("status", "A")).projection(include("item", "status"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- ```java — `findIterable = collection.find(eq("status", "A"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```java — `findIterable = collection.find(eq("status", "A")).projection(exclude("item", "status"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- ```java — `findIterable = collection.find(eq("status", "A")).projection(include("item", "status", "size.uom"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- ```java — `findIterable = collection.find(eq("status", "A")).projection(exclude("size.uom"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- ```java — `findIterable = collection.find(eq("status", "A")).projection(include("item", "status", "instock.qty"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#projection-on-embedded-documents-in-an-array)
- ```java — `findIterable = collection.find(eq("status", "A"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```java — `findPublisher = collection.find(eq("status", "A")).projection(include("item", "status"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- ```java — `findPublisher = collection.find(eq("status", "A"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```java — `findPublisher = collection.find(eq("status", "A")).projection(exclude("item", "status"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- ```java — `findPublisher = collection.find(eq("status", "A")).projection(include("item", "status", "size.uom"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- ```java — `findPublisher = collection.find(eq("status", "A")).projection(exclude("size.uom"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- ```java — `findPublisher = collection.find(eq("status", "A")).projection(include("item", "status", "instock.qty"));` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#projection-on-embedded-documents-in-an-array)
- ```java — `findPublisher = collection.find(eq("status", "A"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```kotlin — `val findFlow = collection` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- ```kotlin — `val findFlow = collection` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```kotlin — `val findFlow = collection` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- ```kotlin — `val findFlow = collection` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- ```kotlin — `val findFlow = collection` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- ```kotlin — `val findFlow = collection` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#projection-on-embedded-documents-in-an-array)
- ```kotlin — `val findFlow = collection` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```javascript — `const cursor = db.collection('inventory').find({` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-fields-in-matching-documents)
- ```javascript — `const cursor = db` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- ```javascript — `const cursor = db` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- ```javascript — `const cursor = db` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- ```javascript — `const cursor = db` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- ```php — `$cursor = $db->inventory->find(['status' => 'A']);` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-fields-in-matching-documents)
- ```ruby — `client[:inventory].find({ status: 'A' },` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- ```ruby — `client[:inventory].find({ status: 'A' },` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```ruby — `client[:inventory].find({ status: 'A' },` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- ```ruby — `client[:inventory].find({ status: 'A' },` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- ```ruby — `client[:inventory].find({ status: 'A' },` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- ```ruby — `client[:inventory].find({ status: 'A' },` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#projection-on-embedded-documents-in-an-array)
- ```ruby — `client[:inventory].find({ status: 'A' },` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```scala — `findObservable = collection.find(equal("status", "A")).projection(include("item", "status"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- ```scala — `findObservable = collection.find(equal("status", "A"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```scala — `findObservable = collection.find(equal("status", "A")).projection(exclude("item", "status"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- ```scala — `findObservable = collection.find(equal("status", "A")).projection(include("item", "status", "size.uom"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- ```scala — `findObservable = collection.find(equal("status", "A")).projection(exclude("size.uom"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- ```scala — `findObservable = collection.find(equal("status", "A")).projection(include("item", "status", "instock.qty"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#projection-on-embedded-documents-in-an-array)
- ```scala — `findObservable = collection.find(equal("status", "A"))` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```csharp — `var filter = Builders<BsonDocument>.Filter.Eq("status", "A");` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- ```csharp — `var filter = Builders<BsonDocument>.Filter.Eq("status", "A");` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```csharp — `var filter = Builders<BsonDocument>.Filter.Eq("status", "A");` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- ```csharp — `var filter = Builders<BsonDocument>.Filter.Eq("status", "A");` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- ```csharp — `var filter = Builders<BsonDocument>.Filter.Eq("status", "A");` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- ```csharp — `var filter = Builders<BsonDocument>.Filter.Eq("status", "A");` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#projection-on-embedded-documents-in-an-array)
- ```csharp — `var filter = Builders<BsonDocument>.Filter.Eq("status", "A");` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```c# — `Builders<BsonDocument>.Projection.Include("instock.0")` … — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- ```javascript — `db.movies.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#group-by-and-calculate-a-sum)
- ```javascript — `db.movies.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#specify-a-comment)
- ```javascript — `db.suppliers.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionWith.md#duplicate-results)
- ```javascript — `db.placesView.countDocuments( { category: "cafe" } )` … — [source](https://www.mongodb.com/docs/manual/core/views/specify-collation.md#example)
- ```javascript — `{ _id: 0 }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto.md#comparing-different-granularities)
- ```javascript — `"_id" : {` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto.md#single-facet-aggregation)
- ```javascript — `"area" : [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto.md#multi-faceted-aggregation)
- ```javascript — `db.scores.findOneAndDelete(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndDelete.md#projecting-the-deleted-document)
- ```javascript — `try {` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndDelete.md#update-document-with-time-limit)
- ```javascript — `db.images.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/binarySize.md#find-largest-binary-data)
- ```javascript — `db.collection.findAndModify({` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findAndModify.md#syntax)
- ```javascript — `db.books.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#use-accumulator-to-implement-the-avg-operator)
- ```javascript — `db.adminCommand( {` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#syntax)
- ```javascript — `key: {` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#untransformed-example)
- ```javascript — `key: {` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#transformed-example)
- ```javascript — `db.scores.findOneAndReplace(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndReplace.md#project-specific-fields-in-return-document)
- ```javascript — `try {` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndReplace.md#replace-document-with-time-limit)
- ```shell — `{ _id: 0, "a" : "int" },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/type.md#example)
- ```shell — `{ _id: 0, a : 8 },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/type.md#existence-check)
- ```javascript — `db.t.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#convert-from-numeric-types-to-bindata)
- ```javascript — `db.t.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#convert-bindata-to-array)
- ```javascript — `db.examples.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#base-conversion-example)
- ```javascript — `"inprog": [` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.currentOp.md#standalone)
- ```javascript — `shard: '<string>',` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.currentOp.md#resharding-output-example)
- ```javascript — `db.theaters.find(` … — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#embedded-documents)
- ```javascript — `const cursor = collection.find({` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents.md#match-an-embedded-nested-document)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#id-field-generation)
- ```javascript — `{ _id: { year: 1939, rated: 'PASSED' }, count: 1 },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#on-demand-materialized-view-initial-creation)
- ```javascript — `{ _id: { year: 1939, rated: 'PASSED' }, count: 1 },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#on-demand-materialized-view-update-replace-data)
- ```javascript — `db.comments.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-the-pipeline-to-customize-the-merge)
- ```javascript — `[ { _id: '1970-01', count: 71 } ]` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-the-pipeline-to-customize-the-merge)
- ```javascript — `const pipeline = [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-variables-defined-in-the-merge-stage-and-aggregate-command)
- ```javascript — `{ _id: 0, result: Long("0") }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bitAnd.md#bitwise-and-with-a-long-and-integer)
- ```javascript — `db.inventory.find( { price: { $in: [ 7.99, 3.99 ], $in: [ 4.99, 1.99 ] } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/and.md#behavior)
- ```javascript — `db.inventory.find( {` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/and.md#behavior)
- ```javascript — `cursor.returnKey()` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.returnKey.md#definition)
- ```javascript — `cursor.tailable( { awaitData : <boolean> } )` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.tailable.md#definition)
- ```javascript — `db.billing.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateSubtract.md#adjust-for-daylight-savings-time)
- ```javascript — `db.orders.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateDiff.md#elapsed-time)
- ```javascript — `db.subscriptions.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateDiff.md#result-precision)
- ```javascript — `db.events.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateDiff.md#year-boundary-crossing)
- ```javascript — `db.months.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateDiff.md#weeks-per-month)
- ```javascript — `{ _id: 0, artist: 'Blue Öyster Cult', title: 'The Reaper' },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#extend-regex-options-to-match-characters-outside-of-ascii)
- ```javascript — `db.employees.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bsonSize.md#return-document-with-largest-specified-field)
- ```javascript — `db.survey.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/allElementsTrue.md#example)
- ```json — `"type" : "op",` … — [source](https://www.mongodb.com/docs/atlas/data-federation/admin/determine-query-status.md#find-command)
- ```javascript — `{ $limit: <positive 64-bit integer> }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#syntax)
- ```javascript — `db.movies.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-shell)
- ```javascript — `{ $slice: [ <array expression>, <n> ] }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/slice.md#definition)
- ```javascript — `{ $slice: [ <array expression>, <position>, <n> ] }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/slice.md#definition)
- ```javascript — `db.users.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/slice.md#example)
- ```javascript — `db.jsonStrings.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toArray.md#convert-string-to-array)
- ```javascript — `"command": {` … — [source](https://www.mongodb.com/docs/manual/reference/log-messages.md#truncation)
- ```javascript — `"t": { "$date": "2021-03-17T20:30:07.212+01:00" },` … — [source](https://www.mongodb.com/docs/manual/reference/log-messages.md#truncation)
- ```javascript — `db.article.aggregate(` … — [source](https://www.mongodb.com/docs/compass/query/skip.md#how-does-the-compass-query-compare-to-mongodb-and-sql-queries)
- ```javascript — `$skip : 435` … — [source](https://www.mongodb.com/docs/compass/query/skip.md#how-does-the-compass-query-compare-to-mongodb-and-sql-queries)
- ```javascript — `db.donors.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rand.md#generate-random-data-points)
- ```javascript — `db.collection.find(<query>).count()` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#definition)
- ```javascript — `db.orders.find().count()` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#count-all-documents)
- ```javascript — `db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#count-documents-that-match-a-query)
- ```javascript — `db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).limit(5).count(true)` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#limit-documents-in-count)
- ```javascript — `db.birthdays.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/isoDayOfWeek.md#example)
- ```javascript — `db.myCollection.updateOne(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/changeStreamSplitLargeEvent.md#mongodb-shell)
- ```javascript — `db.firstYears.find({}, { _id: 0 } )` … — [source](https://www.mongodb.com/docs/manual/core/views/create-view.md#query-the-view)
- ```javascript — `db.arrayconcat.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/reduce.md#computing-a-multiple-reductions)
- ```javascript — `db.collection.find({description: /August [0-9]+, 1969/}).maxTimeMS(50)` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md#examples)
- ```javascript — `{ status: { $in: [ "A", "D" ] } }` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#specify-conditions-using-query-operators)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#perform-a-single-equality-join-with-lookup)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#use-lookup-with-mergeobjects)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#include-specific-fields-in-output-documents)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#exclude-fields-from-output-documents)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#exclude-fields-from-embedded-documents)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#include-specific-fields-from-embedded-documents)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#include-computed-fields)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#project-new-array-fields)
- ```javascript — `var t = db.myCappedCollection;` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.addOption.md#example)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setUnion.md#example)
- ```javascript — `db.events.find( {}, { _id: 0, type: 1 } )` … — [source](https://www.mongodb.com/docs/manual/tutorial/expire-data.md#expire-documents-with-filter-conditions)
- ```javascript — `db.collection.find(<query>).noCursorTimeout()` … — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.noCursorTimeout.md#definition)
- ```javascript — `{ field: { $in: [ <value1>, <value2>, ... <valueN> ] } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#syntax)
- ```javascript — `db.movies.updateMany(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#match-values-in-an-array)
- ```shell — `db.collection('MyCollection').aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/encStrContains.md#example)
- ```javascript — `db.survey.find(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch.md#example-2)
- ```javascript — `db.getSiblingDB("admin").aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#inactive-sessions)
- ```javascript — `db.collection.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/replaceRoot.md#behavior)
- ```javascript — `db.users.createIndex(` … — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#query-coverage)
- ```javascript — `db.users.find( { name: "Ned Stark", password: { $exists: true } } )` … — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#query-coverage)
- ```javascript — `db.users.find( { name: "Ned Stark", password: { $exists: false } } )` … — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#query-coverage)
- ```javascript — `db.movies.distinct( "imdb.rating", { title: { $regex: /^Toy Story/ } } )` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#return-distinct-values-for-an-embedded-field)
- ```javascript — `{ field: { $not: { <operator-expression> } } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#syntax)
- ```javascript — `db.movies.find( { runtime: { $not: { $gt: 180 } } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#syntax)
- ```javascript — `{ runtime: { $not: { $eq: 120 } } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#syntax)
- ```javascript — `{ runtime: { $ne: 120 } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#syntax)
- ```javascript — `{ runtime: { $not: 120 } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#syntax)
- ```javascript — `db.inventory.find( { $nor: [ { price: 1.99 }, { price: { $exists: false } },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nor.md#nor-and-exists)
- ```javascript — `{ $expr: { <expression> } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#syntax)
- ```javascript — `{ $not: [ <expression> ] }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#definition)
- ```javascript — `{ $match: { $expr: { $lt: [ { $rand: {} }, 0.33 ] } } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sampleRate.md#behavior)
- ```javascript — `{ field: { $exists: <boolean> } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#syntax)
- ```javascript — `db.movies.find( { rated: { $exists: true, $nin: [ "R", "PG-13" ] } } ).limit(5)` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#exists-and-not-equal-to)
- ```javascript — `{ $redact: { $cond: { if: { $eq: [ "$level", 5 ] }, then: "$$PRUNE", else: "$$DESCEND" } } },` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#redact-match-sequence-optimization)
- ```javascript — `{ $match: { year: 2014 } },` … — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#redact-match-sequence-optimization)
- ```javascript — `{ $where: <string|JavaScript Code> }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#syntax)
- ```bash — `db.players.find( { $where: function() {` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#example)
- ```javascript — `db.players.find( {$expr: { $function: {` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#example)
- ```javascript — `db.matchCount.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- ```javascript — `db.movies.find( { cast: { $regex: "^A" } } )` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-an-array-for-an-element)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-an-array-with-compound-filter-conditions-on-the-array-elements)
- ```javascript — `db.movies.find(` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-for-an-array-element-that-meets-multiple-criteria)
- ```text — `{ genres: { $nin: ["Drama"] } }` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-an-array-for-an-element)
- ```text — `{ cast: { $regex: "Olsen$", $eq: "Mary-Kate Olsen" } }` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-an-array-with-compound-filter-conditions-on-the-array-elements)
- ```text — `{ languages: { $elemMatch: { $ne: null, $ne: "English" } } }` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-for-an-array-element-that-meets-multiple-criteria)
- ```javascript — `{ $ne: [ <expression1>, <expression2> ] }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/ne.md#definition)
- ```javascript — `db.bios.find( {` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#query-for-multiple-conditions)
- ```javascript — `db.cakeFlavors.runCommand( {` … — [source](https://www.mongodb.com/docs/manual/reference/command/findAndModify.md#use-variables-in-let)
- ```javascript — `db.inventory.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/getField.md#query-fields-that-contain-periods)
- ```javascript — `db.inventory.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/getField.md#query-a-field-in-a-sub-document)
- ```json — `{$expr: {$eq: ["$encrypted1", "plaintext_value"]}}` … — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/supported-operations.md#supported-query-types-operators)
- ```json — `{$expr: {$eq: ["$encrypted1", "$encrypted2"]}}` … — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/supported-operations.md#supported-query-types-operators)
- ```javascript — `{ field: { $ne: value } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#syntax)
- ```javascript — `db.movies.runCommand( {` … — [source](https://www.mongodb.com/docs/manual/reference/command/find.md#use-variables-in-let)
- ```javascript — `{ field: { $nin: [ <value1>, <value2> ... <valueN> ] } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#syntax)
- ```javascript — `db.movies.updateMany(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#select-on-elements-not-in-an-array)
- ```javascript — `db.movies.find( { metacritic: { $ne: null } } )` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#non-equality-filter)
- ```javascript — `db.movies.find( { metacritic: { $exists: false } } )` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- ```java — `db.inventory.find( { item: { $ne : null} } )` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#non-equality-filter)
- ```ruby — `client[:inventory].find(item: { '$ne' => nil })` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#non-equality-filter)
- ```ruby — `client[:inventory].find(item: { '$exists' => false })` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- ```scala — `collection.find($ne("item", null));` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#non-equality-filter)
- ```javascript — `{ item: { $ne : null } }` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#non-equality-filter)
- ```javascript — `{ item : { $exists: false } }` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- ```javascript — `db.inventory.find( { status: { $ne: "closed", $ne: "archived" } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/and.md#examples)
- ```javascript — `db.inventory.find( { status: { $nin: [ "closed", "archived" ] } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/and.md#examples)
- ```javascript — `db.connectionTime.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateSubtract.md#subtract-a-fixed-amount)
- ```javascript — `{ <field>: { $regex: /pattern/, $options: '<options>' } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#syntax)
- ```sh — `mongodump -d=sample_mflix -c=movies -q='{"year": {"$regex": "20"}}'` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#syntax)
- ```javascript — `{ name: { $regex: /acme.*corp/i, $nin: [ 'acmeblahcorp' ] } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#implicit-and-conditions-for-the-field)
- ```javascript — `{ name: { $regex: /acme.*corp/, $options: "si" } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#x-and-s-options)
- ```javascript — `{ name: { $regex: "(?i)a(?-i)cme" } }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#pcre-versus-javascript)
- ```javascript — `db.products.find( { sku: { $regex: /789$/ } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#perform-a-like-match)
- ```javascript — `db.products.find( { sku: { $regex: /^ABC/i } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#perform-case-insensitive-regular-expression-match)
- ```javascript — `db.products.find( { description: { $regex: /\bline\b/ } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#match-whole-words-only)
- ```javascript — `db.products.find( { description: { $regex: /^S/, $options: 'm' } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#multiline-match-for-lines-starting-with-specified-pattern)
- ```javascript — `db.products.find( { description: { $regex: /S/ } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#multiline-match-for-lines-starting-with-specified-pattern)
- ```javascript — `db.products.find( { description: { $regex: /m.*line/, $options: 'si' } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#use-the-dot-character-to-match-new-line)
- ```javascript — `var pattern = "abc #category code\n123 #item number"` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#ignore-white-spaces-in-pattern)
- ```javascript — `db.products.find( { sku: { $regex: "(?i)a(?-i)bc" } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#use-a-regular-expression-to-match-case-in-strings)
- ```javascript — `db.songs.find( { artist: { $regex: /\byster/ } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#extend-regex-options-to-match-characters-outside-of-ascii)
- ```javascript — `db.songs.find( { artist: { $regex: "(*UCP)/\byster/" } } )` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#extend-regex-options-to-match-characters-outside-of-ascii)
- ```ruby — `client[:inventory].find(status: 'A',` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#specify-and-as-well-as-or-conditions)
- ```javascript — `rated: 'G',` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#specify-and-as-well-as-or-conditions)
- ```javascript — `status: 'A',` … — [source](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#specify-and-as-well-as-or-conditions)
- ```shell — `{ name: { $not: { $eq: "Andrea Le" } } }` … — [source](https://www.mongodb.com/docs/atlas/atlas-ui/query/filter.md#match-by-exclusion-not)
- ```shell — `{ email: { $regex: "andrea_le" } }` … — [source](https://www.mongodb.com/docs/atlas/atlas-ui/query/filter.md#match-by-substring)

## Measurements and reference values

- The pseudo-random cursor walks the B-tree and is not guaranteed uniform; skew is likelier with unbalanced trees, many deleted documents, or many documents invisible to the transaction. For a uniform sample put another stage (such as $match) before $sample or use N above 5%, accepting the scan. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- A community benchmark (July 2022) measured $or rising from 52 ms at 1,000 items to 11,684 ms at 20,000, while $in rose from 45 ms to 236 ms; the $or test had no index, so the comparison is unequal and is only directional evidence that $in scales better. — [source](https://mongodb.com/community/forums/t/performance-of-or-vs-in/175513)
- | 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](https://www.mongodb.com/docs/atlas/monitor-cluster-metrics.md#important-metrics)
- $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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#pseudo-random-cursor-behavior)
- allowDiskUse has no effect on sorts answered by an index, or on blocking sorts that fit under 100 MB. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- A low-selectivity $nin on an indexed array field can be slower with the index than without it. In one forum report, the indexed plan examined about 3 million index keys and took about 1,962 ms; the COLLSCAN took about 107 ms. A document matches $nin only if none of its array keys match. The reporter forced a collection scan with hint({$natural:1}). Single anecdote, not a benchmark. — [source](https://www.mongodb.com/community/forums/t/index-is-slower-when-using-nin/112757)
- Tencent Cloud reports that placing a range field ahead of the sort field forced an in-memory sort, and that reordering to ESR cut an order query from second-level latency to about 10 ms and a report from timeout to 200 ms. These are single-vendor anecdotes, not benchmarks. — [source](https://intl.cloud.tencent.com/document/product/240/80772)
- Queries that involve multiple shards per request are less efficient and do not scale linearly when shards are added. A Netdata guide estimates a scatter-gather query on a 50-shard cluster can use up to 50x the CPU, memory and I/O of a targeted query. The 50x figure is an unbenchmarked estimate, not a measured number. — [source](https://www.mongodb.com/docs/manual/core/sharding-choose-a-shard-key/)
- | **Instance RAM** | **Comparable Tier** | **maxIndexBuildMemoryUsageMegabytes Default** | | --- | --- | --- | | 256GB+ | M200+ | 2048 MB | | 128GB - 256GB | M80-M140 | 1024 MB | | 32GB - 128GB | M50-M60 | 512 MB | | 16GB | M40 | 400 MB | | 8GB | M30 | 250 MB | | 2GB - 4GB | M10-M20 | 100 MB | — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- `$changeStreamSplitLargeEvent` splits events that exceed 16 MB into fragments and returns the fragments sequentially using the change stream cursor. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/changeStreamSplitLargeEvent.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)

## Problems, failure modes and limitations

- | **MongoDB Version** | **Changes** | | --- | --- | | 6.1 | Slow operation log messages include [cache refresh time fields.](https://www.mongodb.com/docs/manual/reference/log-messages.md#std-label-log-messages-cache-refresh-times) | | 6.2 | Slow operation log messages include a `queryFramework` field that indicates which query engine executed the query: `queryFramework: "classic"` indicates that the classic engine executed the query.; `queryFramework: "sbe"` indicates that the slot-based query execution engine executed the query. | | 6.3 | Slow operation log messages and [database profiler](ht — [source](https://www.mongodb.com/docs/manual/reference/log-messages.md#version-specific-changes)
- Sort and limit behave differently in the router. Unsorted results come from a round-robin over shard cursors. With limit(), mongos passes the limit to each shard and re-applies it to the merged result. With skip(), mongos cannot push the skip down: it passes limit+skip to the shards, then skips while assembling results. Deep skip on a sharded collection therefore costs more. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- ESR classification: $ne, $nin and $regex are range operators, not equality. $in alone is equality. With a sort, $in under 201 elements expands and merges via a SORT_MERGE stage (acts like equality); at 201 or more it behaves like a range and later index keys cannot supply the sort. The 201 threshold is documented as not guaranteed across versions. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline/)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#output)
- | 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](https://www.mongodb.com/docs/manual/reference/command/count.md#command-fields)
- You can't configure the threshold that [`$sample`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) uses to determine when to scan the entire collection. The threshold is 5%. If the size is greater than 5% of the total number of documents in the collection, [`$sample`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) performs a [top-k](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-limit-results) sort by a generated random value. The top-k so — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#pseudo-random-cursor-behavior)
- Keyset pagination cannot jump to an arbitrary page, since reaching page N generally means visiting earlier pages, and it does not easily return total counts. It suits infinite scroll and next/previous navigation. Skip-limit suits shallow paging, small datasets and jump-to-page UIs. — [source](https://blog.openreplay.com/pagination-patterns-mongodb/)
- | 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](https://www.mongodb.com/docs/manual/tutorial/evaluate-operation-performance.md#performance-overview)
- | 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](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-api-queryShapeInsights-listQueryShapeSummaries.md#options)
- | Field | Description | | --- | --- | | `version` | A number that indicates the query engine used to complete the query. `1` indicates that the classic engine was used.; `2` indicates that the [slot-based query execution engine](https://www.mongodb.com/docs/manual/reference/sbe.md#std-label-sbe-landing) was used. | | `createdFromQuery` | A document that contains the specific query that resulted in this cache entry. For example: `{ "query" : <document>, "sort" : <document>, "projection" : <document> }` | | `isActive` | A boolean that indicates whether the entry is active or inactive. If active, — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/planCacheStats.md#classic-execution-engine)
- | Field | Type | Literal or Normalized | | --- | --- | --- | | `key.queryShape.filter` | Document | Normalized | | `key.queryShape.sort` | Document | Literal | | `key.queryShape.projection` | Document | Normalized | | `key.queryShape.skip` | Integer | Normalized | | `key.queryShape.limit` | Integer | Normalized | | `key.queryShape.singleBatch` | Boolean | Literal | | `key.queryShape.max` | Document | Normalized | | `key.queryShape.min` | Document | Normalized | | `key.queryShape.returnKey` | Boolean | Literal | | `key.queryShape.showRecordId` | Boolean | Literal | | `key.queryShape.tailable` | — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#find-command-query-shape)
- To use an index for string sorting, the operation must specify the same collation as the index; a different collation means the index cannot supply the string order and a blocking sort results. — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- | Prompt | Response | | --- | --- | | `Count the movies that have a release year of 1999` | `[ { $match: { year: 1999 }, }, { $count: "total_movies", } ]` | | `Which comedy genre movie has the most awards?` | `[ { $match: { genres: "Comedy" } }, { $sort: { "awards.wins": -1, "awards.nominations": -1 } }, { $limit: 1 }, { $project: { _id: 0, title: 1, "awards.wins": 1, "awards.nominations": 1 } } ]` | | `How many movies have a imdb.rating > 4?` | `[ { $match: { "imdb.rating": { $gt: 4 } } }, { $group: { _id: null, count: { $sum: 1 } } } ]` | — [source](https://www.mongodb.com/docs/compass/query-with-natural-language/prompt-natural-language-aggregation.md#examples)
- - [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g., [`$gt`](https://www.mongodb.com/docs/manual/reference/operator/query/gt.md#mongodb-query-op.-gt), [`$in`](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#mongodb-query-op.-in)). — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#considerations)
- A count of the number of documents that match the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) query after applying any [`cursor.skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) and [`cursor.limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) methods. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.size.md)
- If the query limits the size of the result set using the limit() cursor method, the mongos instance passes that limit to the shards and then re-applies the limit to the result before returning the result to the client. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- If the query specifies a number of records to skip using the skip() cursor method, the mongos cannot pass the skip to the shards, but rather retrieves unskipped results from the shards and skips the appropriate number of documents when assembling the complete result. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- | Parameter | Type | Description | | --- | --- | --- | | `applySkipLimit` | boolean | Optional. [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) ignores any value you set for this option. The value defaults to `true`. The option specifies whether to consider the effects of the [`cursor.skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) and [`cursor.limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) methods in the count. By default, the [`count()`]( — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md#behaviors)
- When used in conjunction with a [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit), the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) passes the *limit* plus the value of the [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) to the shards to improve the efficiency of these operations. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#skips)
- - Limit the amount of data to sort by using [`cursor.limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) with [`cursor.sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort). See [Limit Results](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-limit-results) for more information and examples. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#sort-and-index-use)
- 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](https://www.netdata.cloud/guides/mongodb/mongodb-scatter-gather-queries/)
- If MongoDB cannot obtain the sort order with an index scan, then MongoDB uses a top-k sort algorithm. This algorithm buffers the first `k` results (or last, depending on the sort order) seen so far by the underlying index or collection access. If the memory footprint of these `k` results exceeds 100 megabytes, MongoDB automatically writes temporary files to disk unless the query specifies [`cursor.allowDiskUse()`](https://www.mongodb.com/docs/manual/reference/method/cursor.allowdiskuse.md#mongodb-method-cursor.allowDiskUse) with a value of `false` (in which case, the query fails). — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#limit-results)
- Since reading.timestamp is not included in an index, MongoDB must perform an in-memory sort operation to return results in the requested sort order. By specifying cursor.allowDiskUse(false), MongoDB cannot process the sort operation if it requires more than 100 megabytes of system memory. If the operation requires more than 100 megabytes of system memory, MongoDB would return an error. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- ESR guideline: $in used alone is an equality operator (a series of equality matches). With .sort(), an $in of fewer than 201 elements is expanded and merged in index sort order by a SORT_MERGE stage, behaving like equality; with 201 or more elements it is ordered like a range, subsequent index fields cannot be used for sorting, and it behaves like a range predicate. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline/)
- distinct on a dotted field cannot be covered (SERVER-2104), and SERVER-23582 (closed 2016-05-17) reported the planner choosing a non-multikey DISTINCT_SCAN with a FETCH that cost more than a collection scan; check explain on dotted-field distincts. — [source](https://jira.mongodb.org/browse/SERVER-23582)
- | 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](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- | 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#parameters)
- | 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](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-api-performanceAdvisor-listSuggestedIndexes.md#options)
- The optimization still applies when `allowDiskUse` is `true` and the `n` items exceed the [aggregation memory limit.](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#std-label-agg-memory-restrictions) — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#sort-limit-coalescence)
- | Field | Type | Description | | --- | --- | --- | | `key` | document | Specifies the index's fields. For each field, specify a key-value pair in which the key is the name of the field to index and the value is either the index direction or [index type](https://www.mongodb.com/docs/manual/core/indexes/index-types.md#std-label-index-types). If specifying direction, specify `1` for ascending or `-1` for descending. MongoDB supports several different index types, including: [text](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-feature-text); [geospatial — [source](https://www.mongodb.com/docs/manual/reference/command/createIndexes.md#command-fields)
- [ { "x.a": { $gt: 85 } }, { "x.b": { $gt: 80 } } ]` However, you can specify compound conditions on the same identifier in a single filter document, such as in the following examples: `// Example 1 [ { $or: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] } ] // Example 2 [ { $and: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] } ] // Example 3 [ { "x.a": { $gt: 85 }, "x.b": { $gt: 80 } } ]` For examples, see [Array Update Operations with `arrayFilters`.](https://www.mongodb.com/docs/manual/reference/command/findandmodify.md#std-label-findAndModify-command-arrayFilters) `arrayFilters` is not available for u — [source](https://www.mongodb.com/docs/manual/reference/command/findAndModify.md#command-fields)
- | Option | Description | More Information | | --- | --- | --- | | Create unique index | Ensure that the indexed fields do not store duplicate values. You cannot perform a rolling build for a unique index. If you enable building indexes in a rolling fashion with the `unique` index option, Atlas rejects your configuration with an error message. | [Unique Indexes](https://www.mongodb.com/docs/manual/core/index-unique/) | | Index name | Specify a name for the index. | [Specify an Index Name](https://www.mongodb.com/docs/manual/core/indexes/create-index/specify-index-name.md#std-label-specify-index — [source](https://www.mongodb.com/docs/atlas/atlas-ui/indexes.md#create-an-index)
- | Parameter | Type | Description | | --- | --- | --- | | `filter` | document | The selection criteria for the deletion. The same [query selectors](https://www.mongodb.com/docs/manual/reference/mql/query-predicates.md#std-label-query-selectors) as in the [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method are available. Specify an empty document `{ }` to delete the first document returned in the collection. If unspecified, defaults to an empty document. If the query argument is not a document, the operation errors. | | — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndDelete.md#parameters)
- | Field | Type | Description | | --- | --- | --- | | `query` | document | Optional. The query predicate of the plan cache query shape. Only the structure of the predicate, including the field names, are significant to the shape; the values in the query predicate are insignificant. | | `projection` | document | Optional. The projection associated with the plan cache query shape. | | `sort` | document | Optional. The sort associated with the plan cache query shape. | | `comment` | any | Optional. A user-provided comment to attach to this command. Once set, this comment appears alongside records — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheClear.md#command-fields)
- 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](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#queries-with-sort)
- A $limit caps the final output across shards, not per shard. A forum participant states mongos can still receive up to N documents from each shard (up to shards*N total) because it cannot know the global top N before merging sorted per-shard streams. The thread has no accepted answer; the two repliers differ on intermediate transfer. — [source](https://www.mongodb.com/community/forums/t/limit-in-a-scatter-and-gather-query-to-a-sharded-collection/237373)
- You can't configure the threshold that $sample uses to determine when to scan the entire collection. The threshold is 5%. If the size is greater than 5% of the total number of documents in the collection, $sample performs a top-k sort by a generated random value. The top-k sort could spill to disk if the sample documents are larger than 100MB. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- When a [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) precedes a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) and there are no intervening stages that modify the number of documents, the optimizer can coalesce the [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) into the [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort). This a — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#sort-and-limit-memory-optimization)
- Use [`allowDiskUse()`](https://www.mongodb.com/docs/manual/reference/method/cursor.allowdiskuse.md#mongodb-method-cursor.allowDiskUse) to either allow or prohibit writing temporary files on disk when a pipeline stage exceeds the 100 megabyte limit. Starting in MongoDB 6.0, operations that require greater than 100 megabytes of memory automatically write data to temporary files by default. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse.md#definition)
- If MongoDB cannot use an index to obtain the sort order, the plan contains an in-memory (blocking) SORT stage; a sort served by an index has no SORT stage and generally performs better. — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- | 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](https://www.mongodb.com/docs/manual/tutorial/evaluate-operation-performance.md#analyze-a-slow-query)
- | Name | Type | Required | Description | | --- | --- | --- | --- | | --clusterName | string | true | Human-readable label that identifies the cluster. | | --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 str — [source](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-api-queryShapeInsights-getQueryShapeDetails.md#options)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md)
- 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](https://www.mongodb.com/docs/manual/reference/command/getMore.md)
- When you chain [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) and [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit), the method chaining order does not affect the results. The server always applies the skip operation based on the sort order before it applies the limit on how many documents to return. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#using-skip-with-limit)
- The following code example shows different chaining orders for [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) and [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) that always produce the same query results for the same data set: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#using-skip-with-limit)
- You can use [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) in conjunction with [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) to return the first (in terms of the sort order) `k` documents, where `k` is the specified limit. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#limit-results)
- Use [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) with [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) to return the top matching documents. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#return-top-2-matching-documents)
- However, the following query cannot use the partial index on the `name` field because using the index results in an incomplete result set. Specifically, the query predicate includes the condition `password: { $exists: false }` while the index has the filter `password: { $exists: true }`. That is, the query `{ name: "Ned Stark", password: { $exists: false } }` matches more documents (users without passwords) than the index covers. — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#query-coverage)
- Use the [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) method on a cursor to specify the maximum number of documents the cursor will return. [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) is analogous to the `LIMIT` statement in a SQL database. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#definition)
- You must apply [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) to the cursor before retrieving any documents from the database. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#definition)
- Use [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) to maximize performance and prevent MongoDB from returning more results than required for processing. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#definition)
- The [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) method has the following prototype form: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#definition)
- The behavior of [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) is undefined for values less than -2 31 and greater than 2 31. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#supported-values)
- You must specify a numeric value for [`limit()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#supported-values)
- A [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) value of 0 (i.e. [`.limit(0)`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit)) is equivalent to setting no limit. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#zero-value)
- The [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) method limits the number of documents in the result set. The following operation returns at most `5` documents in the [bios collection:](https://www.mongodb.com/docs/manual/reference/bios-example-collection.md#std-label-bios-example-collection) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#limit-the-number-of-documents-to-return)
- The following statements chain cursor methods [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) and [`sort()`:](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#combine-cursor-methods)
- The two statements are equivalent; i.e. the order in which you chain the [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) and the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) methods is not significant. Both statements return the first five documents, as determined by the ascending sort order on 'name'. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#combine-cursor-methods)
- MongoDB cursors return results in batches. If you know the number of results you want, specify that value in the limit() method. Limiting results reduces the demand on network resources. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- For more information on limiting results, see [`limit()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#limit-query-results)
- When used in conjunction with a limit(), the mongos passes the limit plus the value of the skip() to the shards to improve the efficiency of these operations. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- MongoDB orders the results by their distance from `[ -74 , 40 ]`. The operation returns the first 100 results, unless you modify the query with the [`cursor.limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) method. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/maxDistance.md#example)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#count-and-transactions)
- - Use the [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match), [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit), and [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) stages to restrict the documents that enter the pipeline. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#document-filters)
- [Multikey indexes](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#std-label-index-type-multikey) cannot cover queries over array fields. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#multikey-covering)
- 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](https://www.mongodb.com/docs/manual/reference/command/distinct/)
- Very large $or lists were slow in the planner because IndexBoundsBuilder::unionize() merged clause bounds one at a time (roughly quadratic); SERVER-34012 was fixed in 5.0.0-rc0. The reporter's diagnostic patch cut a 20,000-clause query from ~40 s to ~400 ms; the official fix's gain is not stated. — [source](https://jira.mongodb.org/browse/SERVER-34012)
- Not every index type can cover queries; hashed indexes cannot be multikey, and support must be checked on each index type's docs page. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- Even when a query cannot be covered, projecting only needed fields reduces network traffic and processing time; coverage additionally removes document reads, so a covered design should index filter fields first (ESR order) and then projected-only fields. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- If MongoDB cannot use an index or indexes to obtain the sort order, MongoDB must perform an in-memory sort operation on the data. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#sort-and-index-use)
- You *cannot* use `$regex` operator expressions inside an [`$in`](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#mongodb-query-op.-in) operator. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#in-expressions)
- If MongoDB cannot use an index or indexes to obtain the sort order, the results include a `SORT` stage indicating an in-memory sort operation. If the explain plan does not contain an explicit `SORT` stage, then MongoDB used an index to obtain the sort order. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#sort-stage)
- db.movies.find( { rated: { $exists: true } }, { _id: 0, title: 1, rated: 1 } ).limit( 3 ) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists/)
- db.movies.find( { rated: { $exists: false } }, { _id: 0, title: 1, year: 1 } ).limit( 3 ) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists/)
- For example, a comparison between `$a` and a constant value can use an index, but a comparison between `$a` and `$b` cannot. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#expr-in-lookup-operations)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#count-command-query-shape)
- Case-insensitive indexes (collation) do not help $regex, because $regex is not collation-aware. The case-insensitive (i) option therefore forfeits efficient prefix bounds. The wording 'cannot use any index' is stronger than the docs; the safer reading is 'no efficient bounds', and explain() decides. — [source](https://www.mongodb.com/docs/current/reference/operator/query/regex/)
- $where evaluates JavaScript for each document and cannot take advantage of indexes. Alone it requires a collection scan. MongoDB evaluates the non-$where predicates first, and those can use an index, so always pair $where with at least one indexable standard predicate. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md)
- $exists:false cannot use a sparse index (requires a COLLSCAN) and requires a FETCH on a non-sparse index. $exists:true is most efficient on a sparse index (exact match, no FETCH). To exclude null and missing values, {field:{$ne:null}} avoids needing a sparse index. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists/)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/planCacheStats.md#definition)
- When a query specifies an exact match for an array as a whole, MongoDB uses the multikey index to locate documents that contain the first element of that array. However, it cannot match the entire array using the index alone. MongoDB then fetches the candidate documents and filters them to return only those whose array exactly matches the query array. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey/)
- 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](https://www.mongodb.com/docs/manual/reference/command/createIndexes/)
- 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](https://www.mongodb.com/docs/manual/reference/database-profiler/)
- | Name | Type | Required | Description | | --- | --- | --- | --- | | --collectionName | string | true | Human-readable label that identifies the collection. | | --databaseName | string | true | Human-readable label that identifies the database. | | --end | string | false | Date and time when MongoDB Cloud stops reporting the metrics. This parameter expresses its value in the ISO 8601 timestamp format in UTC. Include this parameter when you do not set **period**. | | --envelope | envelope | false | Flag that indicates whether Application wraps the response in an envelope JSON object. Some API c — [source](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-api-monitoringAndLogs-getIndexMeasurements.md#options)
- - 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](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#restrictions)
- System indexes are not limited to `maxNumActiveUserIndexBuilds`, however a system index build counts against the limit for user index builds. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- - 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](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#behavior)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-best-practices.md#use-group-instead-of-distinct)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/substrCP.md#definition)
- - 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndexes.md#stable-api)
- If you cannot stop all writes to the collection during this procedure, do not use the procedure on this page. Instead, build your unique index on the collection by issuing [`db.collection.createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createindex.md#mongodb-method-db.collection.createIndex) on the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) for a sharded cluster. — [source](https://www.mongodb.com/docs/manual/tutorial/build-indexes-on-sharded-clusters.md#unique-indexes)
- | 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](https://www.mongodb.com/docs/manual/reference/command/createIndexes.md#command-fields)
- | Rule | Valid Example | Invalid Example | | --- | --- | --- | | If you specify a `wildcardProjection`, it cannot be empty. | `{ productId: 1, "$**": 1 }, { wildcardProjection: { attributes: 1 } }` | `{ productId: 1, "$**": 1 }, { wildcardProjection: { } }` | | You can only combine inclusions and exclusions in a `wildcardProjection` if the included or excluded field is `_id`. You can exclude `_id` in inclusion projections or include `_id` in exclusion projections. | `{ "$**": 1, category: 1 }, { wildcardProjection: { _id: 0, attributes: 1 } }` `{ "$**": 1, category: 1 }, { wildcardProjection: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#wildcardprojection-validation-rules)
- - 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](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#group-optimization)
- - 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](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#lookup-optimization)
- [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch), [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice), and [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) are the *only* operators that you can use to project specific elements to include in the returned array. For instance, you *cannot* project specific array elements using the array index; e.g. `{ "instock.0": 1 }` projection does *not — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch), [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice), and [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) are the *only* operators that you can use to project specific elements to include in the returned array. For instance, you *cannot* project specific array elements using the array index; e.g. `include("instock.0")` projection does *n — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch), [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice), and [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) are the *only* operators that you can use to project specific elements to include in the returned array. For instance, you *cannot* project specific array elements using the array index; e.g. `{ "instock.0" => 1 }` projection does *n — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch), [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice), and [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) are the only operators that you can use to project specific elements to include in the returned array. For instance, you cannot project specific array elements using the array index; e.g. `{ "instock.0": 1 }` projection does not proj — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/substrBytes.md#behavior)
- You cannot cursor.hint() a hidden index. — [source](https://www.mongodb.com/docs/manual/core/index-hidden/)
- 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](https://www.mongodb.com/docs/manual/core/index-sparse.md#sparse-index-and-incomplete-results)
- | 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](https://www.mongodb.com/docs/manual/reference/command/setIndexCommitQuorum.md#command-fields)
- Multikey indexes can cover queries over non-array fields (the index tracks which fields make it multikey) but cannot cover queries over array fields. A multikey index covers a query only if the projection does not return the array field and the query does not use $elemMatch; to cover a query that filters on the array field, the index must be compound. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- To confirm coverage, read explain("executionStats"): look for IXSCAN directly under PROJECTION_COVERED with no FETCH and totalDocsExamined: 0. Flexible schema means MongoDB cannot assume indexed fields exist in all documents, so any projection not fully satisfied by index keys keeps FETCH. — [source](https://dev.to/franckpachot/index-only-scan-on-json-documents-with-covering-and-multi-key-indexes-in-mongodb-53h4)
- Starting in MongoDB 6.0, a pipeline stage or sort needing more than 100 MB of memory writes temporary files to disk by default; passing allowDiskUse: false restores the error-on-overflow behavior. Before 6.0 the sort failed unless allowDiskUse was set. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- However, the following query cannot use the index because it includes a null match on the `email` field, which is not permitted by the filter expression `{ email: { $exists: true } }`: — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#comparison-with-sparse-indexes)
- | `$exists` Query | Using a Sparse Index | Using a Non-Sparse Index | | --- | --- | --- | | `{ $exists: true }` | Most efficient. MongoDB can make an exact match and does not require a `FETCH`. | More efficient than queries without an index, but still requires a `FETCH`. | | `{ $exists: false }` | Cannot use the index and requires a `COLLSCAN`. | Requires a `FETCH`. | — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- - In general, you should use [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) only when you cannot express your query using another operator. If you must use [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where), try to include at least one other standard query operator to filter the result set. Using [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) alone requires a collection scan. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#considerations)
- Pattern names describe plans at a coarse level. They omit limit and skip stages, and they don't distinguish whether a stage applies a filter or which type of projection a plan uses. To determine those details, combine a pattern counter with the nodes counters and the query shape for the entry. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- keyVaultDb := "encryption" keyVaultColl := "__keyVault" keyVaultNamespace := keyVaultDb + "." + keyVaultColl keyVaultIndex := mongo.IndexModel{ Keys: bson.D{{"keyAltNames", 1}}, Options: options.Index(). SetUnique(true). SetPartialFilterExpression(bson.D{ {"keyAltNames", bson.D{ {"$exists", true}, }}, }), } // Drop the Key Vault Collection in case you created this collection // in a previous run of this application. if err = keyVaultClient.Database(keyVaultDb).Collection(keyVaultColl).Drop(context.TODO()); err != nil { log.Fatalf("Collection.Drop error: %v", err) } _, err = keyVaultClient.Data — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/tutorials/explicit-encryption.md#procedure)
- Case-insensitive indexes do not improve performance for [`$regex`](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#mongodb-query-op.-regex) queries, as the `$regex` operator is not collation-aware and therefore cannot take advantage of such indexes. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#case-insensitive-queries)
- If a given field is an array in any document in the collection, wildcard indexes cannot support queries for documents where that field is not equal to `null`. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#array-field-is-not-equal-to-null)
- For example, consider an `inventory` collection with a wildcard index on `product_attributes`. The wildcard index **cannot** support the following queries if `product_attributes.tags` is an array in any document in the collection: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#array-field-is-not-equal-to-null)
- Wildcard indexes store entries for the contents of a document or array, not the document or array itself. Therefore, wildcard indexes cannot support exact equality matches on documents or arrays. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#equality-matches-on-documents-and-arrays)
- For example, consider an `inventory` collection with a wildcard index on `product_attributes`. The wildcard index cannot support the following queries: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#equality-matches-on-documents-and-arrays)
- Similarly, wildcard indexes cannot support exact **inequality** matches on documents and arrays. For example, a wildcard index on `product_attributes` cannot support the following queries: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#equality-matches-on-documents-and-arrays)
- Wildcard indexes are [sparse](https://www.mongodb.com/docs/manual/core/index-sparse.md#std-label-index-type-sparse) and do not index empty fields. Therefore, wildcard indexes cannot support queries for documents where a field does not exist. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#field-does-not-exist)
- For example, consider an `inventory` collection with a wildcard index on `product_attributes`. The wildcard index cannot support all of the predicates in the following query: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#multi-field-query-predicates)
- Query settings have more functionality than index filters. Also, index filters aren't persistent and you cannot easily create index filters for all cluster nodes. To add query settings and explore examples, see [`setQuerySettings`.](https://www.mongodb.com/docs/manual/reference/command/setquerysettings.md#mongodb-dbcommand-dbcmd.setQuerySettings) — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-and-collation)
- - The Performance Advisor cannot suggest indexes for MongoDB databases configured to use the [ctime timestamp format](https://www.mongodb.com/docs/manual/reference/program/mongod/#cmdoption-mongod-timestampformat). As a workaround, set the timestamp format for such databases to either [iso8601-utc](https://www.mongodb.com/docs/manual/reference/program/mongod/#cmdoption-mongod-timestampformat) or [iso8601-local.](https://www.mongodb.com/docs/manual/reference/program/mongod/#cmdoption-mongod-timestampformat) — [source](https://www.mongodb.com/docs/atlas/analyze-slow-queries.md#best-practices-for-query-performance)
- A hexadecimal string that represents the hash of the [plan cache query shape](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-plan-cache-query-shape) and is dependent only on the plan cache query shapes. `planCacheShapeHash` can help identify slow queries (including the query filter of write operations) with the same plan cache query shape. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- This allows the sort operation to only maintain the top `n` results as it progresses, where `n` is the specified limit, and MongoDB only needs to store `n` items in memory . See [$sort Operator and Memory](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#std-label-sort-and-memory) for more information. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#sort-limit-coalescence)
- The optimizer performs [`$sort` + `$limit` Coalescence](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#std-label-agg-sort-limit-coalescence) to transforms the sequence to the following: — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#sort-skip-limit-sequence)
- Scatter-gather is not always bad. For aggregation queries over a large amount of data, MongoDB docs say scatter-gather lets the query run in parallel on all shards and can be useful. The warning targets frequent, latency-sensitive queries. — [source](https://www.mongodb.com/docs/manual/core/sharding-choose-a-shard-key/)
- If the [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage exceeds 100 megabytes of RAM, MongoDB writes data to temporary files. However, if the [allowDiskUse](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#std-label-aggregate-cmd-allowDiskUse) option is set to `false`, `$group` returns an error. For more information, refer to [aggregation pipeline limits.](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#std-label-agg-pipeline-limits) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-and-memory-restrictions)
- If the [`$graphLookup`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphlookup.md#mongodb-pipeline-pipe.-graphLookup) stage exceeds 100 megabytes of memory and the `allowDiskUse` option is set to `false`, [`$graphLookup`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphlookup.md#mongodb-pipeline-pipe.-graphLookup) returns an error. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphLookup.md#memory)
- Aggregation pipelines which call `$bottom` are subject to the [100 MB limit](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#std-label-agg-memory-restrictions). If this limit is exceeded for an individual group, the aggregation fails with an error. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bottom.md#memory-limit-considerations)
- Starting in MongoDB 8.3, the query engine limits the `TextOr` stage memory usage to 100 megabytes. The `TextOr` stage processes [`$text`](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#mongodb-query-op.-text) queries that read text score metadata. For example, `TextOr` processes queries that sort results by text score. If the `TextOr` stage exceeds this limit: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#memory-limits)
- - If `allowDiskUse` is `false`, the query fails with an exceeded memory limit error. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#memory-limits)
- - If [`allowDiskUseByDefault`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.allowDiskUseByDefault) is set to `false`, pipeline stages that require more than 100 megabytes of memory to execute raise an error by default. You can enable writing temporary files to disk for specific `find` or `aggregate` using the `{ allowDiskUse: true }` option. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#memory-restrictions)
- Some stages can't output any documents until they have processed all incoming documents. These pipeline stages must keep their stage output in RAM until all incoming documents are processed. As a result, these pipeline stages may require more space than the 100 MB limit. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#memory-restrictions)
- For memory-intensive expressions that the per-operation limit does not cover, MongoDB applies a limit on the maximum memory that a subset of expressions can use. The default of this limit is 100 megabytes. To change this limit, set the [`internalQueryMaxSingleExpressionMemoryUsageBytes`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.internalQueryMaxSingleExpressionMemoryUsageBytes) parameter at startup or at runtime. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#per-operation-memory-limit)
- As each stage in a `$facet` executes, the resulting document is limited to 100 megabytes. Note the [allowDiskUse](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#std-label-aggregate-cmd-allowDiskUse) flag doesn't affect the 100 megabyte size limit, since `$facet` can't spill to disk. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/facet.md#considerations)
- The view's underlying aggregation pipeline is subject to the 100 megabyte memory limit for blocking sort and blocking group operations. — [source](https://www.mongodb.com/docs/manual/core/views.md#view-pipelines)
- The [`$bucket`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#mongodb-pipeline-pipe.-bucket) stage has a limit of 100 megabytes of RAM. By default, if the stage exceeds this limit, [`$bucket`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#mongodb-pipeline-pipe.-bucket) returns an error. To allow more space for stage processing, use the [allowDiskUse](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#std-label-aggregate-cmd-allowDiskUse) option to enable aggregation pipeline stages to write data to temporary files. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#bucket-and-memory-restrictions)
- Sort stages, counted separately by sort type and by whether the sort has a limit. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- The [`$bucketAuto`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketauto.md#mongodb-pipeline-pipe.-bucketAuto) stage has a limit of 100 megabytes of RAM. By default, if the stage exceeds this limit, MongoDB automatically writes temporary files to disk. For details, see [`allowDiskUseByDefault`.](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.allowDiskUseByDefault) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto.md#bucketauto-and-memory-restrictions)
- - A single [`$accumulator`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#mongodb-group-grp.-accumulator) operation exceeds its specified memory limit. If you specify the [`allowDiskUse`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) option, the operator stores the in-progress operation on disk and finishes the operation in memory. Once the operation finishes, the results from disk and memory are merged together using the [merge](https://www.mongodb.com/docs/manual/reference/operator/a — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#merge-two-states-with-merge)
- Slow query log messages contain new metrics if the query execution writes temporary files to disk. These metrics are prefixed by the query execution stage that caused the query to exceed the memory limit. For example, sortSpills indicates the number of times that the sort stage of query execution wrote temporary files to disk. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- MongoDB writes this log message only when an operation exceeds the per-operation memory limit and cannot spill to disk. If a stage that can spill to disk exceeds the limit and allowDiskUse is false, MongoDB ends the operation with the QueryExceededMemoryLimitNoDiskUseAllowed error and does not write this log message. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- - The [`$function`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/function.md#mongodb-expression-exp.-function) and [`$accumulator`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#mongodb-group-grp.-accumulator) allows users to define custom aggregation expressions in JavaScript if the provided pipeline operators cannot fulfill your application's needs. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/function.md#alternative-to-where)
- Server-side JavaScript ($where, $function, $accumulator) is reported deprecated from MongoDB 8.0 with a server warning. The fetched $where and $function pages do not state this, so the claim rests on one search-result excerpt of the current manual and is unverified. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md)
- Server-side scripting can be turned off (security.javascriptEnabled=false or --noscripting) when no $where, $function, $accumulator or mapReduce is used. This removes the anti-pattern at the configuration level. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md)
- To learn more about related pipeline stages, see the [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) guide. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear.md#learn-more)
- | 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](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-api-alerts-listAlerts.md#options)
- You cannot use the following query operators as part of the query expression for `countDocuments()`: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#query-restrictions)
- The [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) projection operator takes an explicit condition argument. This allows you to project based on a condition not in the query, or if you need to project based on multiple fields in the array's embedded documents. See [Array Field Limitations](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#std-label-array-field-limitation) for an example. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#usage-considerations)
- You can use the [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) operator to limit an `<array>` field, which does not appear in the [query document](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#std-label-read-operations-query-argument). In previous versions of MongoDB, the `<array>` field being limited **must** appear in the query document. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#syntax)
- To ensure expected behavior, the arrays used in the query document and the projection document must be the same length. If the arrays are different lengths, the operation may error in certain scenarios. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#syntax)
- [`$in`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#mongodb-expression-exp.-in) fails with an error in either of the following cases: if the $in expression is not given exactly two arguments, or if the second argument does not resolve to an array. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#return-in-natural-order)
- [`find`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) and [`findAndModify`](https://www.mongodb.com/docs/manual/reference/method/db.collection.findandmodify.md#mongodb-method-db.collection.findAndModify) projection cannot contain both a [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) of an array and a field embedded in the array. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#path-collision-slice-of-an-array-and-embedded-fields)
- - [profiler log messages](https://www.mongodb.com/docs/manual/tutorial/manage-the-database-profiler.md#std-label-database-profiler) and [diagnostic log messages (i.e. mongod/mongos log messages)](https://www.mongodb.com/docs/manual/reference/log-messages.md#std-label-log-messages-ref) when logging slow queries. — [source](https://www.mongodb.com/docs/manual/core/query-plans.md#availability)
- 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](https://www.mongodb.com/docs/manual/reference/operator/query/nearSphere.md#memory-use)
- Starting in MongoDB 5.0, the [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) pipeline aggregation has a 64-bit integer limit. Values passed to the pipeline which exceed this limit will return a invalid argument error. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#high-latency-lookup-operations)
- - `$text` cannot appear in [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/query/elemmatch.md#mongodb-query-op.-elemMatch) query or projection expressions. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#restrictions)
- - Queries with `$text` cannot use [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural) sort. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#restrictions)
- | 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](https://www.mongodb.com/docs/manual/reference/command/getMore.md#command-fields)
- For cursors created inside a session, you cannot call `getMore` outside the session. — [source](https://www.mongodb.com/docs/manual/reference/command/getMore.md#sessions)
- For cursors created outside a session, you cannot call `getMore` inside a session. — [source](https://www.mongodb.com/docs/manual/reference/command/getMore.md#sessions)
- - 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](https://www.mongodb.com/docs/manual/reference/command/getMore.md#transactions)
- - 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](https://www.mongodb.com/docs/manual/reference/command/getMore.md#transactions)
- 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](https://www.mongodb.com/docs/manual/reference/command/getMore.md#errors)
- 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](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#result-size-restrictions)
- If the results of one of your [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) pipeline stages exceed the limit, consider [adding a $limit stage.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#std-label-sort-limit-sequence) — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#memory-restrictions)
- - Add a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage after a [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) stage so that the sort keeps only the documents you need. To learn more, see [$sort and $limit Memory Optimization.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#std-label-sort-limit-sequence) — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#per-operation-memory-limit)
- 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](https://www.mongodb.com/docs/manual/reference/command/profile.md#definition)
- For a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance, the command only configures how operations get written to the diagnostic log. You cannot enable the [database profiler](https://www.mongodb.com/docs/manual/tutorial/manage-the-database-profiler.md#std-label-database-profiler) on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance because `mongos` does not have any collections that the profiler can write to. — [source](https://www.mongodb.com/docs/manual/reference/command/profile.md#definition)
- | Field | Type | Description | | --- | --- | --- | | `profile` | int | Configures the profiler level. The following profiler levels are available: `0`The profiler is off and does not collect any data. This is the default profiler level.`1`The profiler collects data for operations that exceed the `slowms` threshold or match a specified [filter.](https://www.mongodb.com/docs/manual/reference/method/db.setprofilinglevel.md#std-label-set-profiling-level-options-filter)When a filter is set:The `slowms` and `sampleRate` options are not used for profiling.; The profiler only captures operations that — [source](https://www.mongodb.com/docs/manual/reference/command/profile.md#command-fields)
- With [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances, the method sets the `slowms`, `sampleRate` and `filter` configuration settings, which configure how operations get written to the diagnostic log. You cannot enable the [Database Profiler](https://www.mongodb.com/docs/manual/tutorial/manage-the-database-profiler.md) on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance because `mongos` does not have any collections that the profiler can write to. The `profile` level m — [source](https://www.mongodb.com/docs/manual/reference/method/db.setProfilingLevel.md#definition)
- Starting in MongoDB 8.3, you cannot specify `SCRAM-SHA-1` for [`authenticationMechanisms`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.authenticationMechanisms) while also specifying [`mongod --tlsFIPSMode`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--tlsFIPSMode) or [`mongos --tlsFIPSMode`.](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-option-mongos.--tlsFIPSMode) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#authentication-parameters)
- [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) / [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) logs a warning on connection if the presented X.509 certificate expires within `30` days of the `mongod/mongos` system clock. Use the [`tlsX509ExpirationWarningThresholdDays`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.tlsX509ExpirationWarningThresholdDays) parameter to control the certificate expiration warning threshold: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#oidcidentityproviders-fields)
- Base delay in milliseconds for the default retry strategy used in internal server-side connections, such as [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) and [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-program-mongod). The server uses this value as the initial delay for exponential backoff between retries on operations that fail due to overload. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- Maximum delay in milliseconds for the default retry strategy used by internal server-side client connections, such as [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) and [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-program-mongod). The server uses this value as the maximum wait time between retries of operations that fail due to overload. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- This parameter controls whether overload-induced retries against other servers in the cluster avoid servers that recently returned an error labeled `SystemOverloadedError`. It affects operations that perform remote targeting, for example when `mongos` retries requests against shard members or when `mongod` performs remote reads during aggregation. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- When you set this parameter to `true`, retry logic for remote targeting prefers non-overloaded members for operations that fail with `SystemOverloadedError`. For example, when `mongos` retries reads: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- The `tcpFastOpenQueueSize` parameter sets the size of the queue of pending TFO connections. While the queue is full, the `mongod/mongos` falls back to the normal three-way handshake for incoming client requests and ignores the presence of TFO cookies. Once the queue size falls back below the limit, the `mongod/mongos` begins accepting new TFO cookies. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- Configure the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) to redact any message accompanying a given log event before logging. This prevents the program from writing potentially sensitive data stored on the database to the diagnostic log. Metadata such as error or operation codes, line numbers, and source file names are still visible in the logs. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#logging-parameters)
- By default, a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) with [TLS/SSL enabled](https://www.mongodb.com/docs/manual/tutorial/configure-ssl.md#std-label-configure-mongod-mongos-for-tls-ssl) and `net.ssl.allowConnectionsWithoutCertificates` : `true` lets clients connect without providing a certificate for validation while logging an warning. Set `suppressNoTLSPeerCertificateWarning` to `1` or `true` to suppress those warnings. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#logging-parameters)
- If the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) cannot create the specified directory, the diagnostic data capture is disabled for that instance. [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) may not be able to create the specified directory if a file with the same name already exists in the path or if the process does not have permissions to create the directory. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#diagnostic-parameters)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- When set on a sharded cluster with a single shard, enables direct connection warnings. If a user connects directly to the single-shard cluster, `mongod` logs a warning every hour and updates [`shardingStatistics.unauthorizedDirectShardOps`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.shardingStatistics.unauthorizedDirectShardOps) with unauthorized direct shard operations. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- If [`metadataRefreshInTransactionMaxWaitBehindCritSecMS`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.metadataRefreshInTransactionMaxWaitBehindCritSecMS) is too low, [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) could use all of its retry attempts and return an error. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- If [`metadataRefreshInTransactionMaxWaitMS`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.metadataRefreshInTransactionMaxWaitMS) is too low, [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) could use all of its retry attempts and return an error. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- On a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance, this parameter sets the policy that determines the minimum size limit of its connection pools to nodes within replica sets. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- The amount of time to wait from a [Health Managers Overview](https://www.mongodb.com/docs/manual/administration/health-managers.md#std-label-health-managers-overview) failure until the [mongos](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) is removed from the cluster, in seconds. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#health-manager-parameters)
- When a failure is detected and a Health Manager is configured as `critical`, the server waits for the specified interval before removing the `mongos` from the cluster. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#health-manager-parameters)
- | Intensity Level | Description | | --- | --- | | `critical` | The Health Manager on this facet is enabled and has the ability to move the failing [mongos](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) out of the cluster if an error occurs. The Health Manager waits the amount of time specified by [`activeFaultDurationSecs`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.activeFaultDurationSecs) before stopping and moving the [mongos](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) out — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#intensity-levels)
- If [runtime audit configuration](https://www.mongodb.com/docs/manual/tutorial/configure-audit-filters.md#std-label-configure-audit-filters-at-runtime) is enabled, the [`auditAuthorizationSuccess`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.auditAuthorizationSuccess) parameter should not appear in the `mongod` or `mongos` configuration file. The server will fail to start if the parameter is present. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#auditing-parameters)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#transaction-parameters)
- - 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#transactions)
- - You cannot use `$listSampledQueries` directly against a [`--shardsvr`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--shardsvr) replica set. When running on a sharded cluster, `$listSampledQueries` must run against a `mongos`. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listSampledQueries.md#limitations)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.maxAwaitTimeMS.md#definition)
- [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) corresponds to the `LIMIT ...` clause in a SQL (Structured Query Language) `SELECT` statement. — [source](https://www.mongodb.com/docs/compass/query/limit.md#how-does-the-compass-query-compare-to-mongodb-and-sql-queries)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#negative-values)
- To learn more about related pipeline stages, see the [`$bucketAuto`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketauto.md#mongodb-pipeline-pipe.-bucketAuto), [`$sortByCount`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortbycount.md#mongodb-pipeline-pipe.-sortByCount), and [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) guides. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/facet.md#learn-more)
- 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](https://www.mongodb.com/docs/manual/reference/command/distinct/)
- For sharded collections, you cannot use the db.collection.distinct() method or the distinct command. — [source](https://www.mongodb.com/docs/manual/reference/command/distinct/)
- - 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](https://www.mongodb.com/docs/manual/tutorial/query-documents/specify-query-timeout.md#specify-a-time-limit-for-queries)
- When a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) immediately follows another [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit), the two stages can coalesce into a single [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) where the limit amount is the *smaller* of the two initial limit amounts. For example, a pipeline contains the following sequence: — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#limit-limit-coalescence)
- Then the second [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage can coalesce into the first [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage and result in a single [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage where the limit amount `10` is the minimum of the two initial limits `100` and `10`. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#limit-limit-coalescence)
- A pipeline contains a sequence of [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) followed by a [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) followed by a [`$limit`:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#sort-skip-limit-sequence)
- - MongoDB enforces additional restrictions with regards to projections. See [Projection Restrictions](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-Projection-Restrictions) for details. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#projection)
- A `projection` *cannot* contain *both* include and exclude specifications, with the exception of the `_id` field: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#inclusion-or-exclusion)
- | 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#bucketcatalog)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- `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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#opcounters)
- Calculated across all shards, the highest estimate of the number of seconds remaining. If the time estimate cannot be computed, the value is set to -1. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- Calculated across all shards, the lowest estimate of the number of seconds remaining. If the time estimate cannot be computed, the value is set to -1. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- 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](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- The [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) and [`findAndModify()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.findandmodify.md#mongodb-method-db.collection.findAndModify) projection cannot project a field that starts with `$` with the exception of the [DBRef fields.](https://www.mongodb.com/docs/manual/reference/database-references.md#std-label-dbref-explanation) — [source](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) and [`findAndModify()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.findandmodify.md#mongodb-method-db.collection.findAndModify) projection cannot include a projection of an empty field name. — [source](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- 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](https://www.mongodb.com/docs/manual/reference/limits.md#sessions)
- On hosts with Cyrus SASL 2.1.28 or later, MongoDB does not support LDAP SASL binding with the `DIGEST-MD5` mechanism. If you set [`security.ldap.bind.method`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-security.ldap.bind.method) to `sasl` and specify `DIGEST-MD5` in [`security.ldap.bind.saslMechanisms`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-security.ldap.bind.saslMechanisms), `mongod` and `mongos` fail to start. — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#ldap-authentication-or-authorization-options)
- 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](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-estimate-storage-impact.md#steps)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#sessions)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#sessions)
- The following query uses multiple `options` in a single query. This query uses `limit` set to `2` to return only two documents, and `showRecordId` set to `true` to return the position of the document in the result set: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#specify-multiple-options-in-a-query)
- - [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) restricts the output to 5 genres. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/first.md#examples)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md#definition)
- | 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](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md#definition)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#syntax)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- By default, queries in MongoDB return all fields in matching documents. To limit the amount of data that MongoDB sends to applications, you can include a [projection](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-projection) document to specify or restrict fields to return. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md)
- With the exception of the `_id` field, you cannot combine inclusion and exclusion statements in projection documents. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#specify-an-initial-batch-size)
- For more information on limiting results, see limit(). — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- In MongoDB versions earlier than 6.0, if the `findAndModify` command is run on a sharded cluster, [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) discards the [`writeConcernError`](https://www.mongodb.com/docs/manual/reference/method/bulkwriteresult.md#mongodb-data-writeConcernError) document if the shard response contains an error. In MongoDB 6.0 and later, [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) returns `writeConcernError`. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findAndModify.md#write-concern-errors)
- - Uses [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) and [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) to show the first five genres alphabetically. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bottomN.md#find-the-lowest-rated-movies-for-each-genre)
- - 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-the-pipeline-to-customize-the-merge)
- $or supports geospatial clauses. However, if you use a near clause ($near or $nearSphere), $or cannot contain any other clauses. Using $or with a single clause has the same effect as omitting the $or operator. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/or/)
- // Stage 3: Limit the results to 3 documents { $limit: 3 }, — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- Next, create a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to the pipeline to output only the first three documents in the results. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- ```python pipeline.append({"$limit": 3}) — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- Next, add a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to the pipeline to output only the first three documents in the results. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- ```c "{", "$limit", BCON_INT32(3), "}", ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- ```javascript pipeline.push({ $limit: 3, }); — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- ```ruby { "$limit": 3 }, ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- ```rust pipeline.push(doc! { "$limit": 3 }); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- | Name | Type | Required | Description | | --- | --- | --- | --- | | -c, --compact | | false | Flag that enables the compact array response structure for a json output. The --compact option returns array objects as top-level responses and allows backward compatibility for scripts based on previous CLI versions. Omitting the --compact option for a json output returns array objects within a 'results' sub-array. You must specify --output json to use this option. | | -h, --help | | false | help for list | | --limit | int | false | Number of items per results page, up to a maximum of 500. If you — [source](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-alerts-settings-list.md#options)
- You can use `$limit` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#compatibility)
- The [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage has the following prototype form: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#syntax)
- [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) takes a positive integer that specifies the maximum number of documents to pass along. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#syntax)
- This operation returns only the first 5 documents passed to it by the pipeline. [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) has no effect on the content of the documents it passes. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-shell)
- To learn how to use [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) in a full example, see the [Filter Data in an Aggregation Pipeline](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#std-label-agg-example-filter-data) tutorial. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#learn-more)
- - Uses [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) to return the top 5 results. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/stdDevPop.md#example)
- | Operand | Description | | --- | --- | | `<array expression>` | Any valid [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) if it resolves to an array. | | `<position>` | Optional. Any valid [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) if it resolves to an integer. If positive, [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/slice.md#mongodb-expression-exp.-slice) determines the starting position from the start of the array. If `<posi — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/slice.md#definition)
- All updateOne(), replaceOne() and deleteOne() operations must include the shard key or _id in the query document. MongoDB returns an error if these methods are used without the shard key or _id. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- The mongos binary cannot connect to mongod instances whose feature compatibility version (FCV) is greater than that of the mongos. For example, you cannot connect a MongoDB 4.0 version mongos to a 4.2 sharded cluster with FCV set to 4.2. You can, however, connect a MongoDB 4.0 version mongos to a 4.2 sharded cluster with FCV set to 4.0. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- The [profiler entries](https://www.mongodb.com/docs/manual/tutorial/manage-the-database-profiler.md#std-label-database-profiler) and the [diagnostic log messages (i.e. mongod/mongos logmessages)](https://www.mongodb.com/docs/manual/reference/log-messages.md#std-label-log-message-slow-ops) for read/write operations include: — [source](https://www.mongodb.com/docs/manual/reference/log-messages.md#logging-slow-operations)
- In this example, the `$lookup` stage always outputs a `product_mapping` array that contains one document. The `$set` stage after the `$lookup` stage uses `$first` to extract the document from the `product_mapping` array. If you use this pipeline in a setting where the `$lookup` stage outputs an array of more than one document, consider using an explicit `{ $limit: 1 }` stage in the `$lookup` stage. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/one-to-one-join.md#steps)
- - Query `filter`, `projection`, `sort`, `skip`, `limit`, and other operations for [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) are converted to the equivalent [aggregation pipeline stages.](https://www.mongodb.com/docs/manual/reference/mql/aggregation-stages.md#std-label-aggregation-pipeline-operator-reference) — [source](https://www.mongodb.com/docs/manual/core/views/create-view.md#aggregation-optimizations)
- Specifies a cumulative time limit in milliseconds for processing operations on a cursor. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md#definition)
- | Parameter | Type | Description | | --- | --- | --- | | `milliseconds` | integer | Specifies a cumulative time limit in milliseconds for processing operations on the cursor. | — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md#behaviors)
- Queries that generate multiple batches of results continue to return batches until the cursor exceeds its allotted time limit. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md#behaviors)
- When you run the sh.shardCollection() method, the balancer begins distributing the collection data to other shards in the cluster. A single shard can only participate in one chunk migration at a time. When MongoDB succeeds in copying a range of data from one shard to another, the range on the donor shard is marked for removal by the range deleter. This process is slow and resource intensive. — [source](https://www.mongodb.com/docs/manual/sharding/)
- - Response Length: Unusually large response lengths indicate that queries are returning more data than necessary. Consider using [projections](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#std-label-projections) to limit the fields returned. — [source](https://www.mongodb.com/docs/atlas/tutorial/query-profiler.md#find-slow-queries-with-the-query-profiler)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#full-document-lookup-of-update-operations)
- You cannot specify both an embedded document and a field within that embedded document in the same projection. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#path-collision-errors-in-embedded-fields)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.addOption.md#definition)
- | Name | Type | Required | Description | | --- | --- | --- | --- | | -h, --help | | false | help for list | | --limit | int | false | Number of items per results page, up to a maximum of 500. If you have more than 500 results, specify the --page option to change the results page. This value defaults to 100. | | --omitCount | | false | Flag that indicates whether the JSON response returns the total number of items (totalCount) in the JSON response. | | -o, --output | string | false | Output format. Valid values are json, json-path, go-template, or go-template-file. To see the full output, use — [source](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-alerts-list.md#options)
- Response Length: Unusually large response lengths indicate that queries are returning more data than necessary. Consider using projections to limit the fields returned. — [source](https://www.mongodb.com/docs/atlas/tutorial/query-profiler/)
- You cannot apply cursor methods to the result of `findOne()` because a single document is returned. You have access to the document directly: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne.md#the-findone-result-document)
- - You cannot specify a [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) operator in an [`$elemMatch`.](https://www.mongodb.com/docs/manual/reference/operator/query/elemmatch.md#mongodb-query-op.-elemMatch) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch.md#behavior)
- | Field | Description | | --- | --- | | `from` | Target collection for the [`$graphLookup`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphlookup.md#mongodb-pipeline-pipe.-graphLookup) operation to search, recursively matching the `connectFromField` to the `connectToField`. The `from` collection must be in the same database as any other collections used in the operation. For sharding support, see [Sharded Collections.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphlookup.md#std-label-graphLookup-sharded-collections) | | `startWith` | [Expressi — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphLookup.md#definition)
- | Field | Description | | --- | --- | | [input](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexmatch.md#std-label-regexMatch-input) | The string on which you wish to apply the [regex pattern](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexmatch.md#std-label-regexMatch-regex). Can be a string or any valid [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) that resolves to a string. | | [regex](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexmatch.md#std-label-r — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexMatch.md#syntax)
- - The `$text` operator expression cannot appear in [`$or`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/or.md#mongodb-expression-exp.-or) or [`$not`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#mongodb-expression-exp.-not) expressions. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#restrictions)
- | Keyword | Type | Definition | Behavior | | --- | --- | --- | --- | | additionalItems | arrays | boolean or object | If an object, must be a valid JSON Schema | | additionalProperties | objects | boolean or object | If `true`, additional fields are allowed. If `false`, they are not. If a valid JSON Schema object is specified, additional fields must validate against the schema. Defaults to `true`. | | allOf | all types | array of JSON Schema objects | Field must match all specified schemas | | anyOf | all types | array of JSON Schema objects | Field must match at least one of the specified sch — [source](https://www.mongodb.com/docs/manual/reference/operator/query/jsonSchema.md#available-keywords)
- - You cannot use [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) in a `$match` stage. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#restrictions)
- [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) no longer supports the deprecated [BSON type](https://www.mongodb.com/docs/manual/reference/bson-types.md#std-label-bson-types) JavaScript code with scope (BSON Type 15). The [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) operator only supports BSON type String (BSON Type 2) or BSON type JavaScript (BSON Type 13). The use of BSON type JavaScript with scope for [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/ — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#syntax)
- [`map-reduce operations`](https://www.mongodb.com/docs/manual/reference/command/mapreduce.md#mongodb-dbcommand-dbcmd.mapReduce) and [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) operator expressions **cannot** access certain global functions or properties, such as `db`, that are available in [`mongosh`.](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#available-javascript-properties-and-functions)
- To find documents that contain BSON regular expressions as values, call `find()` with the `bsonRegExp` option set to `true`. The `bsonRegExp` option allows you to return regular expressions that can't be represented as JavaScript regular expressions. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#query-for-bson-regular-expressions)
- Queries that compare an encrypted field to `null` or a regular expression always throw an error, even if using a supported query operator. — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/supported-operations.md#unsupported-queries)
- | Type | Number | Alias | Notes | | --- | --- | --- | --- | | Double | 1 | "double" | | | String | 2 | "string" | | | Object | 3 | "object" | | | Array | 4 | "array" | | | Binary data | 5 | "binData" | | | Undefined | 6 | "undefined" | Deprecated. | | ObjectId | 7 | "objectId" | | | Boolean | 8 | "bool" | | | Date | 9 | "date" | | | Null | 10 | "null" | | | Regular Expression | 11 | "regex" | | | DBPointer | 12 | "dbPointer" | Deprecated. | | JavaScript | 13 | "javascript" | | | Symbol | 14 | "symbol" | Deprecated. | | JavaScript with scope | 15 | "javascriptWithScope" | Deprecated. | | 32-bit — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/type.md#available-types)

## Comparisons and alternatives

- | Field | Type | Description | | --- | --- | --- | | `find` | string | The name of the collection or [view](https://www.mongodb.com/docs/manual/core/views.md#std-label-views-landing-page) to query. | | `filter` | document | Optional. The query predicate. If unspecified, all documents in the collection match the predicate. | | [sort](https://www.mongodb.com/docs/manual/reference/command/find.md#std-label-find-cmd-sort) | document | Optional. The sort specification for the ordering of the results. | | `projection` | document | Optional. The [projection specification](https://www.mongodb.com/docs — [source](https://www.mongodb.com/docs/manual/reference/command/find.md#command-fields)
- | Option | Description | | --- | --- | | allowDiskUse | Whether or not pipelines that require more than 100 megabytes of memory to execute write to temporary files on disk. For details, see [`cursor.allowDiskUse()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.allowdiskuse.md#mongodb-method-cursor.allowDiskUse) | | allowPartialResults | For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. | | awaitData | If the cursor is a a tailable-await cur — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#options)
- A rooted $or (single top-level $or) with a sort may choose a blocking SORT over a faster SORT_MERGE because the subplanner picks the locally best plan per clause without considering sort order. A SORT stage instead of SORT_MERGE in explain('queryPlanner') diagnoses it. Ticket SERVER-19114 is Backlog/Unresolved, last updated 2025-03-26. — [source](https://jira.mongodb.org/browse/SERVER-19114)
- | Counter | Description | | --- | --- | | `collscanNoFilter``collscanWithFilter` | Collection scan stages, counted separately based on whether the stage applies a filter. | | `ixscanNoFilter``ixscanWithFilter` | Index scan stages, counted separately based on whether the stage applies a filter. | | `fetchNoFilter``fetchWithFilter` | Fetch stages, counted separately based on whether the stage applies a filter. | | `andHashNoFilter``andHashWithFilter` | Hash-based index intersection stages, counted separately based on whether the stage applies a filter. | | `andSorted` | Sorted index intersection — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#node-counters)
- | Field | Type | Description | | --- | --- | --- | | `planCacheSetFilter` | string | The name of the collection for the index filter. | | `query` | document | The query predicate for the index filter. Only the predicate structure, including the field names, is used in the index filter. The field values in the query predicate are not used. Therefore, the query predicate in an index filter is used by similar queries that differ only in the field values. | | `sort` | document | Optional. The sort for the index filter. | | `projection` | document | Optional. The projection for the index filter. | — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#command-fields)
- | Parameter | Type | Description | | --- | --- | --- | | `filter` | document | The selection criteria for the update. The same [query selectors](https://www.mongodb.com/docs/manual/reference/mql/query-predicates.md#std-label-query-selectors) as in the [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method are available. To update the first document returned in the collection, specify an empty document `{ }`. If unspecified, defaults to an empty document. If the query field is not a document, the operation returns an error — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#parameters)
- | Field | Type | Description | | --- | --- | --- | | `query` | document | Optional. The selection criteria for the modification. The `query` field employs the same [query selectors](https://www.mongodb.com/docs/manual/reference/mql/query-predicates.md#std-label-query-selectors) as used in the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method. Although the query may match multiple documents, [`findAndModify`](https://www.mongodb.com/docs/manual/reference/command/findandmodify.md#mongodb-dbcommand-dbcmd.f — [source](https://www.mongodb.com/docs/manual/reference/command/findAndModify.md#command-fields)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- Adding an array field to a compound index to 'complete' coverage can backfire: in a forum case the index became multikey, the plan fell back to PROJECTION_SIMPLE (not covered), and the poster measured 100 s vs 6 s versus the index without the array field (5.1M docs, MongoDB 4.0.10). — [source](https://mongodb.com/community/forums/t/adding-the-projected-fields-to-compound-index-to-create-covered-query-doesnt-improve-performance/199267)
- Range queries can use [indexes](https://www.mongodb.com/docs/manual/indexes.md#std-label-indexes) to avoid scanning unwanted documents, typically yielding better performance as the offset grows compared to using [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) for pagination. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#using-range-queries)
- | 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](https://www.mongodb.com/docs/manual/reference/command/setQuerySettings.md#command-fields)
- | Parameter | Type | Description | | --- | --- | --- | | `unique` | boolean | Optional. Specifies that each index specified in the `keyPatterns` array is a [unique index](https://www.mongodb.com/docs/manual/core/index-unique.md#std-label-index-type-unique). Unique indexes will not accept insertion or update of documents where the index key value matches an existing value in the index. Specify `true` to create a unique index. The default value is `false`. The option is *unavailable* for [hashed indexes.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-hashed.md#std-label-inde — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndexes.md#options-for-all-index-types)
- | Parameter | Type | Description | | --- | --- | --- | | `unique` | boolean | Optional. Creates a unique index so that the collection will not accept insertion or update of documents where the index key value matches an existing value in the index. Specify `true` to create a unique index. The default value is `false`. The option is *unavailable* for [hashed indexes.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-hashed.md#std-label-index-hashed-index) | | `name` | string | Optional. The name of the index. If unspecified, MongoDB generates an index name by concatenating the — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#options-for-all-index-types)
- When a sort is followed by a limit and no index supplies the order, the server keeps only the top k rows (about skip+limit) in sorter memory rather than all matches. It still examines every matching document, so an index-provided order remains the strongest option. — [source](https://codemia.io/knowledge-hub/path/how_does_top-k_sort_algorithm_work_in_mongodb)
- Rewrite negation as a positive predicate where the allowed set is small or known: use $in over the wanted values instead of $nin over excluded values, and add an indexable equality or range predicate so the negation only filters a small residue. — [source](https://www.mongodb.com/community/forums/t/index-is-slower-when-using-nin/112757)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The following example uses the `key` option to specify that the aggregation should use the `location` field values for the `$geoNear` operation rather than the `legacy` field values. The pipeline also uses [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) to return at most 5 documents. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear.md#specify-which-geospatial-index-to-use)
- 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](https://dev.to/franckpachot/firstlast-per-group-postgresql-distinct-on-and-mongodb-distinctscan-performance-1e9d)
- An index covers a query only if all query fields (including those needed internally, e.g. for sharding) and all returned fields are in the same index, and no query field is compared to null ({field: null} or {field: {$eq: null}} cannot be covered). — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- Unlike the [`$in`](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#mongodb-query-op.-in) query operator, the aggregation [`$in`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#mongodb-expression-exp.-in) operator does not support matching by [regular expressions.](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#std-label-query-in-regex) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#definition)
- | Expressions | Rejected Behavior | Example | | --- | --- | --- | | [`$cond`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/cond.md#mongodb-expression-exp.-cond) [`$switch`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/switch.md#mongodb-expression-exp.-switch) | The expression specifies a field whose encryption properties cannot be known until runtime *and* a subsequent aggregation stage includes an expression referencing that field. | `$addFields : { "valueWithUnknownEncryption" : { $cond : { if : { "$encryptedField" : "value" }, then : "$encryptedFi — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/supported-operations.md#supported-aggregation-expressions)
- - Can use `$ne: null` instead of `$exists: true`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- Unanchored $regex (no literal ^ prefix, e.g. /^.*laptop/ or /laptop/) cannot build a range. With an index it may still run a full IXSCAN over every key rather than a COLLSCAN; without an index it scans the collection. Either way cost grows with collection size. — [source](https://www.mongodb.com/docs/current/reference/operator/query/regex/)
- Documented $expr index limits (in the $lookup subpipeline section): only $eq, $lt, $lte, $gt and $gte can use an index, and only for field-vs-constant comparisons. $a vs $b cannot use an index. Multikey, partial and sparse indexes are not used there. The page documents this only for $lookup; the general find() case is not stated in the fetched text. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md)
- | 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](https://www.mongodb.com/docs/manual/reference/command/dropIndexes.md#command-fields)
- `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](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#definition)
- Modifies the cursor to return index keys rather than the documents. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.returnKey.md#definition)
- Number of times a collection scan occurred during query execution. During a collection scan, each document in a collection is compared to the query predicate. Collection scans occur if no appropriate [index](https://www.mongodb.com/docs/manual/indexes.md#std-label-indexes) exists that [covers](https://www.mongodb.com/docs/manual/core/query-optimization.md#std-label-indexes-covered-queries) the query. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#execution-plan-statistics-for-query-with-lookup-pipeline-stage)
- Starting in MongoDB 9.0, you can use the `queryKnobs` setting to override internal server parameters for a single [query shape](https://www.mongodb.com/docs/manual/core/query-shapes.md#std-label-query-shapes) instead of the whole instance. Set the `queryKnobs` field for targeted queries to mitigate the impact of one regressed shape without changing behavior for other workloads on the same deployment. — [source](https://www.mongodb.com/docs/manual/reference/command/setQuerySettings.md#query-knobs)
- Starting in MongoDB 8.0, use query settings instead of adding [index filters](https://www.mongodb.com/docs/manual/core/query-plans.md#std-label-index-filters). Index filters are deprecated starting in MongoDB 8.0. — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-and-collation)
- The 10,000-document rule of thumb for preferring keyset over skip is a practitioner heuristic, not a measured benchmark; OpenReplay gives no timings. The only quantified offset-vs-seek numbers found are from Postgres (LIMIT 100 ~0.06 ms vs OFFSET 5,000,000 ~758 ms), which show the shape of the effect but not MongoDB's magnitude. — [source](https://blog.openreplay.com/pagination-patterns-mongodb/)
- updateOne(), replaceOne() and deleteOne() must include the shard key or _id; otherwise MongoDB returns an error instead of broadcasting. updateMany() and deleteMany() are broadcast unless the query specifies the full shard key. Multi-update operations are always broadcast. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- - [`QueryExceededMemoryLimitNoDiskUseAllowed`](https://www.mongodb.com/docs/manual/reference/error-codes.md#mongodb-error-292) when a stage that can spill to disk exceeds the limit and `allowDiskUse` is `false`. Run the operation with `{ allowDiskUse: true }` so that the stage spills to disk instead of failing. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#per-operation-memory-limit)
- If you run this example, the order of documents in your results might differ from the order of documents on this page because the aggregation pipeline does not contain a sort stage. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/unpack-arrays.md#steps)
- $ne, $nin and $not match documents that lack the field. {$not:{$gt:180}} differs from {$lte:180}, which returns only documents where the field exists. Negation therefore returns a large share of the collection and is poorly selective. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#mechanics)
- Although you can express this query using the [`$or`](https://www.mongodb.com/docs/manual/reference/operator/query/or.md#mongodb-query-op.-or) operator, use the [`$in`](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#mongodb-query-op.-in) operator rather than the [`$or`](https://www.mongodb.com/docs/manual/reference/operator/query/or.md#mongodb-query-op.-or) operator when performing equality checks on the same field. — [source](https://www.mongodb.com/docs/mongodb-shell/crud/read.md#specify-conditions-using-query-operators)
- Running `$currentOp` with [localOps:true](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#std-label-currentOp-stage-localOps) provides a composite view of the in-progress transactions run on that [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), rather than information on individual shards. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#mongos-composite-view-output)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#definition)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#definition)
- The argument to [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) matches elements of the array that `$elemMatch` is projecting. If you specify an equality with a field name to `$elemMatch`, it attempts to match objects within the array. For example, `$elemMatch` attempts to match objects, instead of scalar values, within the array for the following in the projection: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- [`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) do not rely on `disableSplitHorizonIPCheck` for validation at startup. Legacy `mongod` and `mongos` instances that use IP addresses instead of host names can start after an upgrade. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- | Condition | Recommended Alert Threshold: Low Priority | Recommended Alert Threshold: High Priority | Key Insights | | --- | --- | --- | --- | | Oplog Window | < 24h for 5 minutes | < 1h for 10 minutes | Monitor the replication oplog window, together with replication headroom, to determine whether the secondary may soon require a full resync. The replication oplog window often helps to determine in advance the resilience of secondaries to planned and unplanned outages. | | [Election](https://www.mongodb.com/docs/manual/core/replica-set-elections/) events | > 3 for an hour, notify after 5 minu — [source](https://www.mongodb.com/docs/atlas/architecture/current/monitoring-alerts.md#recommended-atlas-alert-configurations)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sampleRate.md#behavior)
- | 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#changestreampreimages)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- Instead of listing the fields to return in the matching document, you can use a projection to exclude specific fields. The following example which returns all fields except for the `status` and the `instock` fields in the matching documents: — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-but-the-excluded-fields)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/strLenBytes.md#behavior)
- | 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](https://www.mongodb.com/docs/manual/reference/method/cursor.tailable.md#definition)
- If you use $or with <expressions> that are equality checks for the value of the same field, use $in instead of $or. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/or/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateDiff.md#year-boundary-crossing)
- See Targeted Operations vs. Broadcast Operations for more on targeted and broadcast operations. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Targeted Operations vs. Broadcast Operations — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rand.md#select-random-items-from-a-collection)
- On a sharded cluster, this is reported on `mongos` instead of `mongod`. On a replica set, this is reported on `mongod`. — [source](https://www.mongodb.com/docs/manual/reference/command/currentOp.md#output-fields)
- | 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#fields)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#resumability)
- | 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](https://www.mongodb.com/docs/manual/reference/method/cursor.addOption.md#flags)
- See [Targeted Operations vs. Broadcast Operations](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#std-label-sharding-query-isolation) for more on targeted and broadcast operations. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#routing-and-results-process)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne.md#definition)
- Older servers label covered plans PROJECTION rather than PROJECTION_COVERED (observed on 4.0 vs 5.0.13), so totalDocsExamined: 0 is the version-robust coverage check. — [source](https://mongodb.com/community/forums/t/adding-the-projected-fields-to-compound-index-to-create-covered-query-doesnt-improve-performance/199267)
- `{ $not: { $gt: 180 } }` differs from the [`$lte`](https://www.mongodb.com/docs/manual/reference/operator/query/lte.md#mongodb-query-op.-lte) operator. `{ $lte: 180 }` returns *only* the documents where the `runtime` field exists and its value is less than or equal to `180`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#syntax)
- For restrictions on syntax use, see [$regex vs. /pattern/ Syntax.](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#std-label-syntax-restrictions) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#syntax)

## Facts and statements

- Mitigations named by the Netdata guide: put the shard key or leading prefix in predicates, set maxTimeMS on unavoidable scatter-gather queries, avoid deep skip() pagination, and re-evaluate the shard key against dominant query shapes. A low-cardinality key (e.g. continent, at most seven chunks) limits scaling regardless of shard count. Single-vendor-blog advice; not independently verified. — [source](https://www.netdata.cloud/guides/mongodb/mongodb-scatter-gather-queries/)
- | Metric | Description | | --- | --- | | Execution Count | Number of queries executed per hour which would be improved. | | Average Execution Time | Current average execution time in milliseconds for affected queries. | | Average Query Targeting | Average number of documents read per document returned by affected 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) | | In Memory Sort | Current number of affected quer — [source](https://www.mongodb.com/docs/atlas/performance-advisor.md#index-metrics)
- Workarounds for the rooted-$or SORT problem: hint one index that serves all clauses to force a merge sort; use an index filter (not persistent across restarts, set per node); or ensure each clause has an index providing the sort order and none offers an index requiring a blocking sort. — [source](https://jira.mongodb.org/browse/SERVER-19114)
- Indexes can also [cover](https://www.mongodb.com/docs/manual/core/query-optimization.md#std-label-covered-queries) [`db.collection.distinct()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#mongodb-method-db.collection.distinct) operations. See [Run Covered Queries](https://www.mongodb.com/docs/manual/core/query-optimization.md#std-label-covered-queries) for more information on queries covered by indexes. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#index-use)
- Sorting on an indexed array field (multikey index) yields an in-memory SORT stage unless the index bounds for all sort fields are [MinKey, MaxKey] and no multikey field bounds share a path prefix with the sort pattern. — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The following example creates an index filter on the `orders` collection such that for queries that consist only of an equality match on the `status` field without any projection and sort, the query optimizer evaluates only the two specified indexes and the collection scan for the winning plan: — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-only)
- For the plan cache query shape, the query optimizer will only consider indexed plans which use the index `{ item: 1, order_date: 1, quantity: 1 }`. — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-projection-and-sort)
- If maxTimeMS equals the driver's client socket timeout, the driver closes the connection first and the server can never return MaxTimeMSExpired, causing connection churn. Set the client timeout above maxTimeMS. — [source](https://jira.mongodb.org/browse/DRIVERS-2971)
- If $in has fewer than 201 array elements, the elements are expanded and then merged in the sort order specified for the index using a SORT_MERGE stage. This improves performance for small arrays. In this case, $in is similar to an equality predicate with ESR. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- cursor.allowDiskUse() has no effect on sort operations answered using an index or non-indexed ("in-memory") sort operations which require less than 100 megabytes of memory. For more complete documentation on in-memory sorts and sort index use, see Sort and Index Use. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- See [Sort and Index Use](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-index-use) for more information on in-memory sort operations. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse.md#definition)
- [`cursor.allowDiskUse()`](https://www.mongodb.com/docs/manual/reference/method/cursor.allowdiskuse.md#mongodb-method-cursor.allowDiskUse) has no effect on sort operations answered using an index *or* non-indexed ("in-memory") sort operations which require less than 100 megabytes of memory. For more complete documentation on in-memory sorts and sort index use, see [Sort and Index Use.](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-index-use) — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse.md#supports-large-non-indexed-sorts-only)
- SERVER-24027 (Core Server, fixed in 3.4.2/3.5.2, closed Jan 2017): for $or keyset pagination sorted descending on a compound key, the planner did not reverse an index scan to get SORT_MERGE and fell back to an in-memory sort. The pre-fix workaround was a descending index plus hint(). On pre-3.4.2 servers, check explain() for SORT or a blocking sort. — [source](https://jira.mongodb.org/browse/SERVER-24027)
- 3. The following example counts the documents where the `metacritic` field has a value (including null) and uses the [sparse index:](https://www.mongodb.com/docs/manual/core/index-sparse.md#std-label-index-type-sparse) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- ```javascript db.movies.countDocuments( { metacritic: { $exists: true } } ) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- The example returns 6964. The operation does not count the documents that are missing the `metacritic` field. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- | Field | Type | Literal or Normalized | | --- | --- | --- | | `key.queryShape.pipeline` | Array | Normalized | | `key.queryShape.explain` | Boolean | Literal | | `key.queryShape.allowDiskUse` | Boolean | Literal | | `key.queryShape.allowPartialResults` | Boolean | Literal | | `key.queryShape.collation` | Document | Literal | | `key.queryShape.hint` | String or Document | Normalized | | `key.queryShape.let` | Document | Normalized | — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#aggregate-command-query-shape)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#count-all-documents-in-a-collection)
- The following code uses the [`cursor.returnKey()`](https://www.mongodb.com/docs/manual/reference/method/cursor.returnkey.md#mongodb-method-cursor.returnKey) method to return only the indexed fields used for executing the query: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.returnKey.md#example)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#definition)
- The following command queries the `movies` collection for movies with an IMDB rating of at least 9 that are in the Drama genre. The command includes a `projection` to return only the `title`, `imdb.rating`, and `year` fields. — [source](https://www.mongodb.com/docs/manual/reference/command/find.md#specify-a-sort-and-limit)
- | Option | Description | More Information | | --- | --- | --- | | Create unique index | Ensure that the indexed fields do not store duplicate values. | [Unique Indexes](https://www.mongodb.com/docs/manual/core/index-unique/) | | Index name | Specify a name for the index. | [Specify an Index Name](https://www.mongodb.com/docs/manual/core/indexes/create-index/specify-index-name.md#std-label-specify-index-name) | | Create a TTL (Time to Live) index | Delete documents automatically after a specified number of seconds since the indexed field value. | [TTL Indexes](https://www.mongodb.com/docs/manua — [source](https://www.mongodb.com/docs/compass/indexes.md#create-an-index)
- | 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](https://www.mongodb.com/docs/atlas/performance-advisor.md#sample-queries)
- 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](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#queries-with-sort)
- 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](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#queries-with-sort)
- The following example creates an index filter for the `orders` collection. The filter applies to queries whose predicate is an equality match on the `item` field, where only the `quantity` field is projected and an ascending sort by `order_date` is specified. — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-projection-and-sort)
- - The query planner selects the wildcard index to fulfill the query predicate. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#covered-queries)
- - The query predicate specifies *exactly* one field covered by the wildcard index. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#covered-queries)
- The following JavaScript function uses [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) to paginate a collection by its `_id` field: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#using-skip)
- The [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) method requires the server to scan from the beginning of the input results set before beginning to return results. As the offset increases, [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) will become slower. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#using-skip)
- - Query for documents whose field is less than the start value using the [`$lt`](https://www.mongodb.com/docs/manual/reference/operator/query/lt.md#mongodb-query-op.-lt) and [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) operators, and — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#descending-order)
- - [`$sample`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#mongodb-pipeline-pipe.-sample) is the first stage of the pipeline. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#pseudo-random-cursor-behavior)
- - A high number of documents aren't visible to the cursor's transaction. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#pseudo-random-cursor-behavior)
- ```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](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#from-the-mongos-instance)
- cursor.allowDiskUse() (mongosh method) — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- The following operation includes a cursor.sort() on the field reading.timestamp. The operation also passes false to cursor.allowDiskUse() to prohibit the query from writing temporary files to disk. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- The following operation includes a [`cursor.sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) on the field `reading.timestamp`. The operation also passes `false` to [`cursor.allowDiskUse()`](https://www.mongodb.com/docs/manual/reference/method/cursor.allowdiskuse.md#mongodb-method-cursor.allowDiskUse) to prohibit the query from writing temporary files to disk. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse.md#example)
- - [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage filters the documents to those returned by the [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) operator. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- ```javascript db.movies.find( { title: { $not: /^T/ }, runtime: { $gt: 1000 } }, { _id: 0, title: 1, runtime: 1 } ) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#regular-expressions)
- A compound index supports a sort on all its keys or on a prefix, with sort keys in index order. Directions must match the index pattern or its exact inverse: {a:1,b:-1} supports {a:1,b:-1} and {a:-1,b:1}, but not {a:1,b:1} or {a:-1,b:-1}. — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- An index can serve a sort on a non-prefix subset of its keys only if the query has equality conditions on all index keys that precede the sort keys. With index {a,b,c,d}, find({a:{$gt:2}}).sort({c:1}) does not use the index efficiently. — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- ESR guideline: put equality keys first, then sort keys, then range keys, so the index delivers sorted output without an in-memory sort. Sorting after equality also makes the sort non-blocking. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline/)
- countDocuments() rejects $where, $near and $nearSphere in its query; the documented substitutes are $expr and $geoWithin with $center / $centerSphere. Inside a transaction, both countDocuments() and estimatedDocumentCount() do not filter out uncommitted multi-document transactions. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- Hashed sharding gives more even distribution at the cost of targeting. Post-hash, documents with close key values are unlikely to share a shard, so mongos is more likely to broadcast a ranged query. Equality matches can still be targeted to a single shard. The docs say 'more likely', not 'always'. — [source](https://www.mongodb.com/docs/manual/core/hashed-sharding/)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#index-use)
- An aggregation pipeline can use [indexes](https://www.mongodb.com/docs/manual/indexes.md#std-label-indexes) from the input collection to improve performance. Using an index limits the amount of documents a stage processes. Ideally, an index can [cover](https://www.mongodb.com/docs/manual/core/query-optimization.md#std-label-read-operations-covered-query) the stage query. A covered query has especially high performance, since the index returns all matching documents. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#indexes)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#queryplanner-mode)
- Wildcard indexes can support a [covered query](https://www.mongodb.com/docs/manual/core/query-optimization.md#std-label-covered-queries) only if **all** of the following conditions are true: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#covered-queries)
- 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](https://www.mongodb.com/docs/manual/reference/command/find.md#override-default-read-concern)
- 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](https://www.mongodb.com/docs/manual/reference/command/find.md#override-default-read-concern)
- 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](https://www.mongodb.com/community/forums/t/mis-understanding-batchsize/169713/2)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md)
- 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](https://www.mongodb.com/docs/manual/core/read-preference.md)
- 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](https://jira.mongodb.org/browse/SERVER-18190)
- Call the [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) method on a cursor to control where MongoDB begins returning results. This approach may be useful in implementing paginated results. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#definition)
- You must apply [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) to the cursor before retrieving any documents from the database. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#definition)
- The [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) method has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- Counts the number of documents remaining in a cursor. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.itcount.md#definition)
- You can specify the [`{ $meta: "textScore" }`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) expression in the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) without also specifying the expression in the projection. For example: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#sort-by-relevance-score)
- If you include the [`{ $meta: "textScore" }`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) expression in both the [projection](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#std-label-find-projection) and [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort), the projection and sort documents can have different field names for the expression. For example, in the following operation, the projection uses a field named `score` for the expression and the [`so — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#sort-by-relevance-score)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.collation.md#examples)
- The following query can use the index since the query predicate includes the condition `password: { $exists: true }` that matches documents matched by the index filter expression `password: { $exists: true }`: — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#query-coverage)
- - In find, the `{ $meta: "textScore" }` expression can be included in [projection](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#std-label-find-projection) and in [`sort()`.](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#availability)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#pseudo-random-cursor-behavior)
- The following table compares `$exists` query performance using sparse and non-sparse indexes: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- A document that returns the open cursor count and open session count for the session. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#wiredtiger)
- The [`skip()`](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#mongodb-method-cursor.skip) method controls the starting point of the results set. The following operation skips the first `5` documents in the [bios collection](https://www.mongodb.com/docs/manual/reference/bios-example-collection.md#std-label-bios-example-collection) and returns all remaining documents: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#set-the-starting-point-of-the-result-set)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md#definition)
- The inequality operator `$ne` is *not* very selective since it often matches a large portion of the index. As a result, in many cases, a `$ne` query with an index may perform no better than a `$ne` query that must scan all documents in a collection. See also [Create Selective Queries.](https://www.mongodb.com/docs/manual/core/query-optimization.md#std-label-read-operations-query-selectivity) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#update-based-on-not-equal-embedded-document-fields)
- The inequality operator [`$nin`](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#mongodb-query-op.-nin) is *not* very selective since it often matches a large portion of the index. As a result, in many cases, a [`$nin`](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#mongodb-query-op.-nin) query with an index may perform no better than a [`$nin`](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#mongodb-query-op.-nin) query that must scan all documents in a collection. See also [Create Selective Queries.](https://www.mongodb.com/docs/ma — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#select-on-elements-not-in-an-array)
- | Field | Type | Description | | --- | --- | --- | | `maxTimeMS` | integer | Optional. The maximum amount of time to allow the count to run. | — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount.md#fields)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#definition)
- The [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) method has the following prototype form: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#definition)
- The [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) method has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#definition)
- The following are examples of the [`count()`](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#mongodb-method-cursor.count) method. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#examples)
- 3. Count the number of documents in the cursor — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#examples)
- - Choose a field such as `_id` which generally changes in a consistent direction over time and has a [unique index](https://www.mongodb.com/docs/manual/core/index-unique.md#std-label-index-type-unique) to prevent duplicate values, — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#descending-order)
- For example, the following operation creates a compound multikey index on the `movies` collection on the `genres` and `title` fields: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#covered-queries)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-best-practices.md#use-group-instead-of-distinct)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#index-bounds)
- - 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#index-bounds)
- - 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#usage)
- The server uses the index the same way, but you may notice a difference in the output of the [`listIndexes`](https://www.mongodb.com/docs/manual/reference/command/listindexes.md#mongodb-dbcommand-dbcmd.listIndexes) and [`db.collection.getIndexes()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.getindexes.md#mongodb-method-db.collection.getIndexes) commands. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/wildcard-projection-signature.md#projection-signature-display)
- - Run `db.collection.createIndex()` on the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) for a sharded cluster — [source](https://www.mongodb.com/docs/manual/core/index-unique.md#building-unique-index-on-replica-sets-and-sharded-clusters)
- - All the fields returned in the results are in the same index. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#run-covered-queries)
- A `movies` collection has the following index on the `rated` and `title` fields: — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#example)
- The index covers the following operation which queries on the `rated` and `title` fields and returns only the `title` field: — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#example)
- An index can cover a query on fields within embedded documents. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#embedded-documents)
- The `{ "location.address.city": 1 }` index covers the following query: — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#embedded-documents)
- Querying *only* the index can be much faster than querying documents outside of the index. Index keys are typically smaller than the documents they catalog, and indexes are typically available in RAM or located sequentially on disk. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#performance)
- Not all [index types](https://www.mongodb.com/docs/manual/core/indexes/index-types.md#std-label-index-types) can cover queries. For details on covered index support, refer to the documentation page for the corresponding index type. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#index-types)
- - `SHARD_MERGE` for merging results from shards — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#classic-execution-engine)
- - `SHARDING_FILTER` for filtering out orphan documents from shards — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#classic-execution-engine)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#index-use)
- Consider the following wildcard index on the `employees` collection: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#covered-queries)
- dbs.forEach((d) => { if (d.name != 'local') { const listCollCursor = db .getSiblingDB(d.name) .runCommand({ listCollections: 1 }).cursor; — [source](https://www.mongodb.com/docs/manual/tutorial/expire-data.md#indexes-configured-using-nan)
- const collDetails = { db: listCollCursor.ns.split(".$cmd")[0], colls: listCollCursor.firstBatch.map((c) => c.name), }; — [source](https://www.mongodb.com/docs/manual/tutorial/expire-data.md#indexes-configured-using-nan)
- MongoDB uses indexes to evaluate an $or only if every clause is supported by an index; if any clause lacks index support, the query performs a collection scan. Each $or clause can use its own index, so separate single-field indexes are recommended over a compound index for different-field clauses. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/or/)
- In explain output an index-union $or appears as an OR stage (often under SUBPLAN) with one IXSCAN child per clause, usually under a FETCH; two IXSCAN children confirm both indexes are used. — [source](https://oneuptime.com/blog/post/2026-03-31-mongodb-index-for-or-queries/view)
- Sort operations that use an index often have better performance than in-memory sorts. For more information on creating indexes to support sort operations, see [Use Indexes to Sort Query Results.](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes.md#std-label-sorting-with-indexes) — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#sort-and-index-use)
- Sort operations that use an index often have better performance than in-memory sorts. — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- ```javascript db.movies.find( { title: { $not: { $regex: "^T" } }, runtime: { $gt: 1000 } }, { _id: 0, title: 1, runtime: 1 } ) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#regular-expressions)
- ```javascript db.movies.find( { title: { $not: { $regex: /^T/ } }, runtime: { $gt: 1000 } }, { _id: 0, title: 1, runtime: 1 } ) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#regular-expressions)
- "Sort" determines the order for results. To avoid in-memory sorts, put sort fields before range in the index. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- See Sort and Index Use for more information on in-memory sort operations. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- MongoDB `$exists` does **not** correspond to SQL operator `exists`. For SQL `exists`, see [`$in`.](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#mongodb-query-op.-in) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#definition)
- MongoDB $exists does not correspond to SQL operator exists. For SQL exists, see $in. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists/)
- The `$in` operator can select documents using regular expressions of the form `/pattern/`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#use-in-with-a-regular-expression)
- - 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](https://www.mongodb.com/docs/manual/reference/command/count.md#inaccurate-counts-without-query-predicate)
- - 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](https://www.mongodb.com/docs/manual/reference/command/count.md#inaccurate-counts-without-query-predicate)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#inaccurate-counts-without-query-predicate)
- A query has a different shape if the query has different specifications. For example, if a query has a different filter, sort, projection, namespace, or aggregation pipeline stages. — [source](https://www.mongodb.com/docs/manual/core/query-shapes/)
- - Indexes can only be used for comparisons between fields and constants, so the `let` operand must resolve to a constant. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#expr-in-lookup-operations)
- - The [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) specifies **only** the query predicate field. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#queries-with-sort)
- 2. Create a [sparse index](https://www.mongodb.com/docs/manual/core/index-sparse.md#std-label-index-type-sparse) on the `metacritic` field: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- The following example uses the [`$ne`](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#mongodb-query-op.-ne) operator to query for all documents where the first element in the `countries` array is not equal to `USA`: — [source](https://www.mongodb.com/docs/manual/tutorial/query-arrays.md#query-for-an-element-by-the-array-index-position)
- For case-sensitive $regex, an index lets MongoDB match the regex against index values, which can beat a collection scan. If the regex is a prefix expression (starts with ^ or \A followed by simple symbols), MongoDB builds an index range from the prefix and scans only that range. — [source](https://www.mongodb.com/docs/current/reference/operator/query/regex/)
- /^a/, /^a.*/ and /^a.*$/ match equivalent strings and all can use an index, but /^a.*/ and /^a.*$/ are slower. /^a/ can stop scanning after the prefix. Write the bare anchored prefix, not a trailing .*. — [source](https://www.mongodb.com/docs/current/reference/operator/query/regex/)
- - 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](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- - With the `secondaryPreferred` read preference, `mongos` can route a retried read to the primary if secondaries indicate overload. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- The [`readConcern()`](https://www.mongodb.com/docs/manual/reference/method/cursor.readconcern.md#mongodb-method-cursor.readConcern) method has the following form: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.readConcern.md#definition)
- The [`readConcern()`](https://www.mongodb.com/docs/manual/reference/method/cursor.readconcern.md#mongodb-method-cursor.readConcern) method has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.readConcern.md#definition)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.readPref.md#parameters)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.readPref.md#specify-read-preference-mode)
- A document that counts how many internal and external read preference operations the node received while serving as the primary. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#readpreferencecounters)
- A document that counts how many internal and external read preference operations the node received while serving as a secondary. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#readpreferencecounters)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#concurrent-updates-while-using-a-cursor)
- 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](https://www.mongodb.com/docs/manual/reference/operator/query/nearSphere.md#2d-index)
- For a complete list of logical query operators, see [Logical Query Operators.](https://www.mongodb.com/docs/manual/reference/mql/query-predicates/logical/) — [source](https://www.mongodb.com/docs/atlas/atlas-ui/query/filter.md#match-by-exclusion-not)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#specify-the-index-to-use)
- | Value | Description | | --- | --- | | `$slice: <number>` | Specifies the number of elements to return in the `<arrayField>`. For `<number>`: Specify a positive number `n` to return the first `n` elements.; Specify a negative number `n` to return the last `n` elements. If the `<number>` is greater than the number of array elements, the query returns all array elements. | | `$slice: [ <number to skip>, <number to return> ]` | Specifies the number of elements to return in the `<arrayField>` after skipping the specified number of elements starting from the first element. You must specify both el — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#syntax)
- The [query optimizer](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-query-optimizer) uses query settings as an additional input during query planning. Index hints in query settings restrict the set of indexes available to the planner, but don't guarantee that the planner will use the index. The planner can still select a collection scan as the winning plan for a given query shape hash. — [source](https://www.mongodb.com/docs/manual/reference/command/setQuerySettings.md#definition)
- A string that specifies whether the cursor uses a collection scan (`COLLSCAN`) or an index scan (`IXSCAN { ... }`). — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- 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](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#queryexecstats-document)
- 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](https://www.mongodb.com/docs/manual/tutorial/measure-index-use.md#control-index-use-with-hint)
- - Query execution stages that buffer records, such as geospatial proximity searches, counts that use an index, and updates — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#per-operation-memory-limit)
- - Atlas always creates indexes for entire clusters. If you create an index while viewing the Performance Advisor for a single shard in a sharded cluster, Atlas creates that index for the entire sharded cluster. — [source](https://www.mongodb.com/docs/atlas/performance-advisor.md#behavior-and-limitations)
- For example, this [`$in`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#mongodb-expression-exp.-in) query benefits from a secondary index on `metadata.type`: — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#use-secondary-indexes-to-improve-sort-performance)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-secondary-index.md#last-point-queries-on-time-series-collections)
- For the query optimizer to choose this partial index, the query predicate must include a condition on the `name` field as well as a *non-null* match on the `email` field. — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#comparison-with-sparse-indexes)
- [`nindexes`](https://www.mongodb.com/docs/manual/reference/command/collstats.md#mongodb-data-collStats.nindexes) includes indexes currently being built in its count. — [source](https://www.mongodb.com/docs/manual/reference/command/collStats.md#output)
- If $in has 201 elements or more, the elements are ordered like a range operator. In this case, the performance improvement for small arrays isn't realized. It isn't possible for the subsequent fields in the index to be used for sorting, and $in is similar to a range predicate with ESR. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- If you typically use $in operators with small arrays, include them earlier in the index specification. If you typically use large arrays, include $in operators where you would include a range predicate. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- Connect [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) to a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance in the sharded cluster and disable migrations for the collection where you want to perform the rolling build index: — [source](https://www.mongodb.com/docs/manual/tutorial/build-indexes-on-sharded-clusters.md#a-stop-migrations)
- - 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#index-bounds)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#example)
- - 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#example)
- - 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#example)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#definition)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#access-documents-in-a-cursor-with-toarray-https-www-mongodb-com-docs-manual-reference-method-cursor-toarray-md-mongodb-method-cursor-toarray)
- Indexes can also cover distinct operations. See Run Covered Queries for more information on queries covered by indexes. — [source](https://www.mongodb.com/docs/manual/reference/command/distinct/)
- For the plan cache query shape, the query optimizer only uses indexed plans that use the index `{ item: 1, order_date: 1, quantity: 1 }`. — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-and-collation)
- - An index on the grouping field that matches the `$sort` order returns all of the field values needed for the `$group` stage, making it a covered query. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#indexes)
- 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](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#indexes)
- 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](https://www.mongodb.com/docs/manual/tutorial/analyze-query-plan/)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#indexstats)
- - Run the [`explain`](https://www.mongodb.com/docs/manual/reference/command/explain.md#mongodb-dbcommand-dbcmd.explain) command on a change stream cursor. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- | 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](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#verbosity-modes)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#queryplanner-mode)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#db-collection-explain-find)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#sharded-clusters)
- [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) operations can return information regarding: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#output)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#example)
- [`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](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#help)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#queryplanner-mode)
- 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](https://www.mongodb.com/docs/manual/administration/monitoring.md#collstats)
- ```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](https://www.mongodb.com/docs/manual/tutorial/manage-indexes.md#find-inconsistent-indexes-across-shards)
- - Issue an index build [`db.collection.createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createindex.md#mongodb-method-db.collection.createIndex) from a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance. The operation only builds the collection's index on the shard(s) missing the index. — [source](https://www.mongodb.com/docs/manual/tutorial/manage-indexes.md#find-inconsistent-indexes-across-shards)
- Starting in MongoDB 6.3, 6.0.5, and 5.0.16, the `wildcardProjection` field stores the index projection in its submitted form. Earlier versions of the server may have stored the projection in a normalized form. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/wildcard-projection-signature.md#projection-signature-display)
- - 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](https://www.mongodb.com/docs/atlas/reference/alert-resolutions/query-targeting.md#fix-the-immediate-problem)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- Scans that count index keys without returning documents. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- The operation returns a document that details the processing of the aggregation pipeline. For example, the document may show, among other details, which index, if any, the operation used. If the `movies` collection is a sharded collection, the document also shows the division of labor between the shards and the merge operation, and for targeted queries, the targeted shards. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#return-information-on-aggregation-pipeline-operation)
- 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](https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency.md#cursor-snapshot)
- 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](https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency.md#cursor-snapshot)
- If the specified lastName is never an array, MongoDB can use the $** wildcard index to support a covered query. — [source](https://www.mongodb.com/docs/manual/core/index-wildcard/)
- For the specified index to cover the query, the projection document must explicitly specify _id: 0 to exclude the _id field from the result since the index doesn't include the _id field. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- For an example of a covered query with a multikey index, see Covered Queries on the multikey indexes page. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#plan-shape-counters)
- 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](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#command-fields)
- For an example of a covered query with a multikey index, see [Covered Queries](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#std-label-multikey-covered-queries) on the multikey indexes page. — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#multikey-covering)
- [`$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](https://www.mongodb.com/docs/manual/reference/method/cursor.returnKey.md#definition)
- If the query does not use an index to perform the read operation, the cursor returns empty documents. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.returnKey.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.tailable.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- 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](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- 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](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- In previous versions of MongoDB, `cursor.explain()` returned the `clauses` array that detailed the indexes. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#or-expression)
- For sharded collections, explain returns the serverInfo for each accessed shard, and a top-level serverInfo object for the mongos. — [source](https://www.mongodb.com/docs/manual/reference/explain-results/)
- The cursor.explain() command for mongosh provides performance details for all queries. — [source](https://www.mongodb.com/docs/atlas/reference/alert-resolutions/query-targeting/)
- 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](https://www.mongodb.com/docs/manual/reference/command/explain.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/command/explain.md#queryplanner-mode)
- 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](https://www.mongodb.com/docs/manual/reference/command/explain.md#executionstats-mode)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- Index placement guidance: put $in earlier in the compound index (equality position) if it typically has small arrays; put it where a range predicate would go if it typically has large arrays. The docs state the 201-element threshold is not guaranteed to stay the same across MongoDB versions, so confirm with explain on the target version. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline/)
- MongoDB's documented range-query pagination: pick a field such as _id that changes consistently over time and has a unique index, filter with $lt (descending) or $gt (ascending), sort on it, and store the last-seen value for the next query. Range queries use indexes to avoid scanning unwanted documents. — [source](https://www.mongodb.com/docs/v8.2/reference/method/cursor.skip/)
- For a non-unique sort field such as createdAt, keyset pagination needs a compound filter: $or of {createdAt < last} and {createdAt == last, _id < lastId}, sorted by {createdAt:-1,_id:-1}, backed by an index with the same fields and directions. — [source](https://blog.openreplay.com/pagination-patterns-mongodb/)
- If the index does not include _id, the projection must explicitly set _id: 0, otherwise the query is not covered. Excluding _id alone (without listing only indexed fields) leaves FETCH then PROJECTION_SIMPLE. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- The $expr operator does not support multikey indexes. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey/)
- This document describes the [`$in`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#mongodb-expression-exp.-in) aggregation operator. For the `$in` query operator, see [$in (query predicate operator).](https://www.mongodb.com/docs/manual/reference/operator/query/in.md) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#definition)
- The [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) operator does not support multikey indexes. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#expr)
- | 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](https://www.mongodb.com/docs/atlas/query-shape-insights.md#report-contents)
- The following operation on the `users` collection creates an index that specifies a [unique constraint](https://www.mongodb.com/docs/manual/core/index-unique.md#std-label-index-type-unique) on the `email` field and a partial filter expression `password: { $exists: true }`. — [source](https://www.mongodb.com/docs/manual/core/index-partial.md#partial-index-with-unique-constraint)
- the fields and operations also supported by the plan cache query shape. Examples: filter, sort, and projection. — [source](https://www.mongodb.com/docs/manual/core/query-shapes/)
- For example, the following [PyMongo](https://pymongo.readthedocs.io/en/stable/index.html) query uses Python's `re.compile()` method to compile a regular expression: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#regular-expressions)
- Queries that use `{ $exists: true }` on fields that use a non-sparse index or that use `{ $exists: true }` on fields that are not indexed examine all documents in a collection. To improve performance, create a [sparse index](https://www.mongodb.com/docs/manual/core/index-sparse.md#std-label-index-type-sparse) on the `field` as shown in the following scenario: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#use-a-sparse-index-to-improve-exists-performance)
- - The non-[`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) query statements may use an [index.](https://www.mongodb.com/docs/manual/reference/command/collmod.md#mongodb-collflag-index) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#considerations)
- | Parameter | Type | Description | | --- | --- | --- | | [query](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#std-label-method-find-query) | document | Optional. Specifies selection filter using [query operators](https://www.mongodb.com/docs/manual/reference/mql/query-predicates.md#std-label-query-projection-operators-top). To return all documents in a collection, omit this parameter or pass an empty document (`{}`). | | [projection](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#std-label-method-find-projection) | document | Optional. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#parameters)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md#definition)
- 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](https://www.mongodb.com/docs/atlas/query-shape-insights/)
- 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](https://www.mongodb.com/docs/atlas/query-shape-insights/)
- The following table describes the query shape properties for count commands. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- The selectivity of regular expressions depends on the expressions themselves. For details, see regular expression and index use. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats.md#query-shape)
- The selectivity of [`regular expressions`](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#mongodb-query-op.-regex) depends on the expressions themselves. For details, see [regular expression and index use.](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#std-label-regex-index-use) — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#create-selective-queries)
- Index use and performance for `$regex` queries depends on whether the query is case-sensitive or case-insensitive. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#index-use)
- For case sensitive regular expression queries, if an index exists for the field, then MongoDB matches the regular expression for the values in the index. This can be faster than a collection scan. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#case-sensitive-queries)
- ```javascript [ { "opid": "12345", "secs_running": 5, "active": true, "ns": "sample_mflix.movies", "command": { "find": "movies", "filter": { "title": { "$regex": "The" } } }, "planSummary": "COLLSCAN", "locks": { ... }, "client": "203.0.113.25:43210" } ] ``` — [source](https://www.mongodb.com/docs/manual/tutorial/monitor-slow-queries.md#steps)
- The original query shape of the mongos operation may differ after the mongos sends the operation to the mongod . — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- The operation uses a query predicate of `{ rated: { $in: [ "G", "PG-13" ] } }`, which corresponds to the following SQL statement: — [source](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#specify-conditions-using-query-operators)
- The operation uses a query predicate of `{ status: { $in: [ "A", "D" ] } }`, which corresponds to the following SQL statement: — [source](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#specify-conditions-using-query-operators)
- This loss of accuracy only applies to `count()` operations that do *not* include a query predicate. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#accuracy-after-unexpected-shutdown)
- The Performance Advisor also shows each executed sample query that matches the query shape, with specific metrics for that query. — [source](https://www.mongodb.com/docs/atlas/performance-advisor.md#sample-queries)
- The following example shows how MongoDB uses bounds intersection to define a smaller range of values to query, resulting in improved query performance. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey/multikey-index-bounds.md#example-bounds-intersection)
- The following example shows how MongoDB uses compound bounds to define a more efficient query constraint, resulting in improved query performance. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey/multikey-index-bounds.md#example-compound-bounds-of-non-array-field-and-array-field)
- The Performance Advisor monitors queries that take longer than `100` milliseconds to execute and groups these queries into common [query shapes](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-query-shape). The Performance Advisor calculates the inefficiency of each query shape by considering the following aggregated metrics from queries which match the shape: — [source](https://www.mongodb.com/docs/atlas/performance-advisor/index-ranking.md#how-performance-advisor-suggests-and-ranks-indexes)
- Wildcard indexes **can** support queries where the field equals an empty document `{}`. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#equality-matches-on-documents-and-arrays)
- In the case that a single wildcard index could support multiple query fields, MongoDB can only use the wildcard index to support one of the query fields. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#multi-field-query-predicates)
- Instead, MongoDB uses the wildcard index to support only one of the query predicates. MongoDB automatically chooses which predicate to support based on relevant wildcard index paths. The unsupported query predicates are shown in the [`rejectedPlans`](https://www.mongodb.com/docs/manual/reference/explain-results.md#mongodb-data-explain.queryPlanner.rejectedPlans) of the [explain results.](https://www.mongodb.com/docs/manual/reference/explain-results.md#std-label-explain-results) — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#multi-field-query-predicates)
- This is also true for compound wildcard indexes. The wildcard term of a compound index can only support one query predicate, although the non-wildcard terms can support the remaining predicates. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#multi-field-query-predicates)
- MongoDB may use the same wildcard index to support each independent argument of the query [`$or`](https://www.mongodb.com/docs/manual/reference/operator/query/or.md#mongodb-query-op.-or) or aggregation [`$or`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/or.md#mongodb-expression-exp.-or) operators. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#multi-field-query-predicates)
- Consider the following wildcard index on the `products` collection: — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#queries-with-sort)
- The following example creates an index filter for the `orders` collection. The filter applies to queries whose predicate is an equality match on the `item` field and the collation `en_US` (English United States). — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-and-collation)
- Starting in MongoDB 6.0, an index filter uses the [collation](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation) previously set using the [`planCacheSetFilter`](https://www.mongodb.com/docs/manual/reference/command/plancachesetfilter.md#mongodb-dbcommand-dbcmd.planCacheSetFilter) command. — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#set-filter-on-plan-cache-query-shape-consisting-of-predicate-and-collation)
- - Create queries that your current indexes support to reduce the time needed to search for your results. — [source](https://www.mongodb.com/docs/atlas/analyze-slow-queries.md#best-practices-for-query-performance)
- - Avoid creating documents with large array fields that require a lot of processing to search and index. — [source](https://www.mongodb.com/docs/atlas/analyze-slow-queries.md#best-practices-for-query-performance)
- - Optimize your indexes and remove unused or inefficient indexes. Too many indexes can negatively impact write performance. — [source](https://www.mongodb.com/docs/atlas/analyze-slow-queries.md#best-practices-for-query-performance)
- - Consider the suggested indexes from the [Performance Advisor](https://www.mongodb.com/docs/atlas/performance-advisor.md#std-label-performance-advisor) with the highest Impact scores and lowest Average Query Targeting scores. — [source](https://www.mongodb.com/docs/atlas/analyze-slow-queries.md#best-practices-for-query-performance)
- - Perform [rolling index builds](https://www.mongodb.com/docs/manual/tutorial/build-indexes-on-replica-sets/#rolling-index-builds-on-replica-sets) to reduce the performance impact of building indexes on [replica sets](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-replica-set) and [sharded clusters.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-sharded-cluster) — [source](https://www.mongodb.com/docs/atlas/analyze-slow-queries.md#best-practices-for-query-performance)
- - [Drop unused, redundant, and hidden indexes](https://www.mongodb.com/docs/atlas/performance-advisor/drop-indexes.md#std-label-pa-drop-index) to improve write performance and free storage space. — [source](https://www.mongodb.com/docs/atlas/analyze-slow-queries.md#best-practices-for-query-performance)
- 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, executes the winning plan to completion, and returns statistics describing the execution of the winning plan. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#executionstats-mode)
- Time in milliseconds the query planner spent on query optimization. This result doesn't include time spent optimizing inner [`$lookup`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#mongodb-pipeline-pipe.-lookup) queries. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- A document that details the plan selected by the [query optimizer.](https://www.mongodb.com/docs/manual/core/query-plans.md) — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- A document that details the plan selected by the [query optimizer](https://www.mongodb.com/docs/manual/core/query-plans.md). MongoDB presents the plan as a tree of stages. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- Array of candidate plans considered and rejected by the query optimizer. The array can be empty if there were no other candidate plans. — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#unsharded-collections)
- Starting in MongoDB 8.0, `explain` outputs the following field: — [source](https://www.mongodb.com/docs/manual/reference/explain-results.md#query-shape-hash)
- 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](https://www.mongodb.com/docs/manual/reference/operator/query/nearSphere.md#2dsphere-index)
- The following query specifies the query predicate `rated: { $exists: true }`: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#exists-true)
- The following query specifies the query predicate `rated: { $exists: false }`: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#exists-false)
- 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](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-geospatial.md#use-cases)
- In the Filter field, enter a filter document between the curly braces. You can use all the MongoDB [query operators](https://www.mongodb.com/docs/manual/reference/mql/query-predicates/) except the [`$text`](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#mongodb-query-op.-text) and [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) operators. — [source](https://www.mongodb.com/docs/atlas/atlas-ui/query/filter.md#set-query-filter)
- Query shape statistics provide performance insights about MongoDB queries, helping users identify problematic query patterns and potential optimizations. — [source](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-api-queryShapeInsights-listQueryShapeSummaries.md)
- The examples on this page use data from the [sample\_mflix dataset](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix). For details on how to load this dataset into your self-managed MongoDB deployment, see [Load the Sample Dataset](https://www.mongodb.com/docs/manual/sample-data/load-sample-data-local.md#std-label-sample-dataset-local). If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#count-the-number-of-documents-in-a-collection)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-year)
- - [`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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-year)
- For example, the following function uses the above procedure to print pages of student names from a collection, sorted approximately in order of newest documents first using the `_id` field (that is, in *descending* order): — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#descending-order)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#count-collection-connections)
- - the `sort` field to the [`findAndModify`](https://www.mongodb.com/docs/manual/reference/command/findandmodify.md#mongodb-dbcommand-dbcmd.findAndModify) command or the [`findAndModify()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.findandmodify.md#mongodb-method-db.collection.findAndModify) shell method, — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#using-skip-with-sorted-results)
- The operation returns the three documents that have `zipcode` value of `"63109"`. The returned documents include the `_id` field and matching elements of the `athletics` array, if any. The operation returns the three documents that have `zipcode` value of `"63109"`. The returned documents include the `_id` field and matching elements of the `athletics` array, if any. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- - 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- - 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-best-practices.md#use-group-instead-of-distinct)
- The aggregation pipeline can determine if it requires only a subset of the fields in the documents to obtain the results. If so, the pipeline only uses those fields, reducing the amount of data passing through the pipeline. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#projection-optimization)
- The following operation finds all documents in the [bios collection](https://www.mongodb.com/docs/manual/reference/bios-example-collection.md) and returns only the `name` field, `contribs` field and `_id` field: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#specify-the-fields-to-return)
- The following operation queries the [bios collection](https://www.mongodb.com/docs/manual/reference/bios-example-collection.md) and returns all fields *except* the `first` field in the `name` embedded document and the `birth` field: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#explicitly-excluded-fields)
- The following operation queries the [bios collection](https://www.mongodb.com/docs/manual/reference/bios-example-collection.md) and returns the `last` field in the `name` embedded document and the first two elements in the `contribs` array: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#on-arrays-and-embedded-documents)
- With the use of aggregation expressions and syntax, you can project new fields or project existing fields with new values. For example, the following operation uses aggregation expressions to override the value of the `name` and `awards` fields as well as to include new fields `reportDate`, `reportBy`, and `reportNumber`. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#use-aggregation-expression)
- [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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#specify-collation)
- The driver provides [com.mongodb.client.model.Filters](https://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/client/model/Filters.html) helper methods to facilitate the creation of filter documents. The examples on this page use these methods to create the filter documents. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- This example uses the [sample movies dataset](https://www.mongodb.com/docs/atlas/sample-data/sample-mflix/). To load the sample dataset into your MongoDB Atlas deployment, see [Load Sample Data.](https://www.mongodb.com/docs/atlas/sample-data/#std-label-load-sample-data) — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-to-return-from-a-query-with-mongodb-atlas)
- Specify the [query filter document](https://www.mongodb.com/docs/manual/core/documents-other-uses.md#std-label-document-query-filter) in the Filter field. A query filter document uses [query operators](https://www.mongodb.com/docs/manual/core/csfle/reference/supported-operations.md#std-label-csfle-supported-query-operators) to specify search conditions. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-to-return-from-a-query-with-mongodb-atlas)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md#session-idle-timeout-overrides-maxtimems)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- [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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- - [`$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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsSecond.md#use-tssecond-in-a-change-stream-cursor-to-monitor-collection-changes)
- If the application is instead connected to a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod), the returned document does not include the `isdbgrid` string. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#confirm-connection-to-mongos-instances)
- For queries that don't include the shard key, [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) must query all shards, wait for their responses and then return the result to the application. These "scatter/gather" queries can be long running operations. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#targeted-operations-vs-broadcast-operations)
- [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances broadcast queries to all shards for the collection **unless** the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) can determine which shard or subset of shards stores this data. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#broadcast-operations)
- The [`updateMany()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.updatemany.md#mongodb-method-db.collection.updateMany) and [`deleteMany()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.deletemany.md#mongodb-method-db.collection.deleteMany) methods are broadcast operations, unless the query document specifies the shard key in full. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#broadcast-operations)
- The [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) program *can* route queries that include the full shard key or either of the following shard key prefixes at a specific shard or set of shards: — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#targeted-operations)
- All [`insertOne()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.insertone.md#mongodb-method-db.collection.insertOne) operations target to one shard. Each document in the [`insertMany()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.insertmany.md#mongodb-method-db.collection.insertMany) array targets to a single shard, but there is no guarantee all documents in the array insert into a single shard. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#targeted-operations)
- Depending on the distribution of data in the cluster and the selectivity of the query, [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) may still perform a [broadcast operation](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#std-label-sharding-mongos-broadcast) to fulfill these queries. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#targeted-operations)
- A query without the shard key is broadcast to all shards for the collection. mongos must query every shard, wait for all responses, then merge. MongoDB calls these scatter/gather queries and says they can be long running. Docs say to favor targeted operations over broadcast ones. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Including the shard key does not guarantee a single-shard route. Depending on data distribution and query selectivity, mongos may still broadcast (for example a range predicate spanning chunks on several shards). — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Starting in MongoDB 6.0, if the server requires more than 100 megabytes of memory for a pipeline execution stage, MongoDB automatically writes temporary files to disk unless that query specifies { allowDiskUse: false }. — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- 2. Add a sort stage to sort by order date. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/group-and-total.md#steps)
- 4. Add a sort stage to sort by first order date. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/group-and-total.md#steps)
- 2) Add a sort stage to sort by order date. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/group-and-total.md#steps)
- 4) Add a sort stage to sort by first order date. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/group-and-total.md#steps)
- - If `allowDiskUse` is `true`, the stage spills intermediate results to disk. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#memory-limits)
- Starting in MongoDB 6.0, the [`allowDiskUseByDefault`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.allowDiskUseByDefault) parameter controls whether pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#memory-restrictions)
- - If [`allowDiskUseByDefault`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.allowDiskUseByDefault) is set to `true`, pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default. You can disable writing temporary files to disk for specific `find` or `aggregate` commands using the `{ allowDiskUse: false }` option. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#memory-restrictions)
- Pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default. These temporary files last for the duration of the pipeline execution and can influence storage space on your instance. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- *Default*: 104857600 (100 megabytes) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- The following command sets `internalQueryMaxSingleExpressionMemoryUsageBytes` to `104857600` (100 megabytes) at runtime: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- The following command sets `internalQueryMaxSingleExpressionMemoryUsageBytes` to `104857600` (100 megabytes) at startup: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- If avoiding in-memory sorts is critical, place sort fields before range fields (ESR) — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- If the range predicate in your query is very selective, place it before the sort fields to reduce the number of sorted documents and allow an in-memory sort. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- db.collection.find(<match>).sort(<sort>).allowDiskUse() — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- Starting in MongoDB 6.0, pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- Prior to MongoDB 6.0, .allowDiskUse(false) and .allowDiskUse(true) have the same effect. In MongoDB 6.0, both mongosh and the legacy mongo shell behave the following way: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- .allowDiskUse() has no additional effect — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- .allowDiskUse(true) has no additional effect — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- .allowDiskUse(false) prohibits the query from writing temporary files to disk — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- .allowDiskUse() enables writing temporary files to disk — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- .allowDiskUse(true) enables writing temporary files to disk — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- .allowDiskUse(false) has no additional effect — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- - If the pipeline includes a sorting or grouping stage, and the [allowDiskUse](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#std-label-aggregate-cmd-allowDiskUse) setting is enabled, the merge runs on a randomly-selected shard. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-sharded-collections.md#behavior)
- A document that holds counters related to sort stages. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The total number of writes to disk caused by sort stages. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The following query uses the `options` parameter to enable `allowDiskUse`: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#allowdiskuse-with-options)
- Sort merge stages, counted separately based on whether the stage applies a filter and whether the stage has more than 100 child stages. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- key.queryShape.allowDiskUse — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- If the query bar is empty, you can click the filter bar to open the query autocomplete menu and view up to 50 recent or favorite queries. To scroll through your most recent queries, you can use the up ↑ and down ↓ arrow keys. If a query is highlighted on the menu, it displays a pop-up panel that shows the filter, project, and sort stages of the query. To select a query from the autocomplete menu, press Enter, press Tab, or click the query. — [source](https://www.mongodb.com/docs/atlas/atlas-ui/query/recent.md#query-autocomplete-menu)
- 2) Add a sort stage to sort from youngest to oldest. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- 2. Add a sort stage to sort from youngest to oldest. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- For more information on writing temporary files to disk, see allowDiskUse(). — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- An estimated number of bytes processed in the $sort stage. — [source](https://www.mongodb.com/docs/manual/reference/explain-results/)
- The following aggregation uses [`$regexMatch`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexmatch.md#mongodb-expression-exp.-regexMatch) to filter for `items` that have a `name` value that starts with `p`: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter.md#filter-based-on-regular-expression-match)
- Starting in version 6.1, MongoDB uses the PCRE2 (Perl Compatible Regular Expressions) library to implement regular expression pattern matching. To learn more about PCRE2, see the [PCRE Documentation.](https://www.pcre.org/current/doc/html/) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexMatch.md#pcre-library)
- | Document | Weighted Score | > 9 | | --- | --- | --- | | `{ title: "The Shawshank Redemption", imdb: { rating: 9.3, votes: 1521105 } }` | 9.3 | `true` | | `{ title: "The Godfather", imdb: { rating: 9.2, votes: 1038358 } }` | 9.2 | `true` | | `{ title: "Fight Club", imdb: { rating: 8.9, votes: 1191784 } }` | 8.9 | `false` | | `{ title: "Planet Earth", imdb: { rating: 9.5, votes: 82896 } }` | 9.5 | `true` | | `{ title: "Hollywood", imdb: { rating: 9.1, votes: 511 } }` | 4.55 | `false` | — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#use-expr-with-conditional-statements)
- The [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) operation returns 5 documents whose calculated weighted score is greater than `9`: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#use-expr-with-conditional-statements)
- Even though [`$cond`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/cond.md#mongodb-expression-exp.-cond) calculates a weighted score, that score is not reflected in the returned documents. Instead, the returned documents represent the matching documents in their original state. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#use-expr-with-conditional-statements)
- The example can be expressed using [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) and [`$function`:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/function.md#mongodb-expression-exp.-function) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/function.md#example-2-alternative-to-where)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#count-the-number-of-documents-in-a-collection)
- The [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage filters the resulting documents to return only ratings with a `totalRuntime` greater than or equal to 100000. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-rating)
- The following pipeline calculates the total runtime, average runtime, and movie count for each year before 1910: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-year)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-year)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#group-by-null)
- mongod log messages, in the attr.command.cursor.comment field. — [source](https://www.mongodb.com/docs/manual/reference/command/setindexcommitquorum/)
- You may then use the following code to print all student names using this pagination function, using [`MaxKey`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-MaxKey) to start from the largest possible key: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.skip.md#descending-order)
- The query meets all other covered query requirements. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey/)
- The `countDocuments()` method has the following form: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#syntax)
- The `countDocuments()` method takes the following parameters: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#parameters)
- | 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#parameters)
- `countDocuments()` wraps the following aggregation operation and returns just the value of `n`: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#mechanics)
- `countDocuments()` returns `0` on an empty or non-existing collection or view. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#empty-or-non-existing-collections-and-views)
- `countDocuments()` can be used inside [distributed transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#transactions)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#client-disconnection)
- The positional [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) operator limits the contents of an `<array>` to return the first element that matches the query condition on the array. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#definition)
- The [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) operator projects the first matching array element from each document in a collection based on some condition from the query statement. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#usage-considerations)
- [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) operations on [views](https://www.mongodb.com/docs/manual/core/views.md#std-label-views-landing-page) do not support [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) projection operator. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#usage-considerations)
- - Only one positional [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) operator may appear in the projection document. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#array-field-limitations)
- You must use the [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) operator if you need separate conditions for selecting documents and for choosing fields within those documents. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#array-field-limitations)
- The [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) projection operator can only appear at the end of the field path, for example `"field.$"` or `"fieldA.fieldB.$"`. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#positional-operator-placement-restriction)
- In previous versions, MongoDB returns the first element (`instock.$`) in the `instock` array that matches the query condition; i.e. the positional projection `"instock.$"` takes precedence and the `$slice:1` is a no-op. The `"instock.$": { $slice: 1 }` does not exclude any other document field. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#positional-operator-and-slice-restriction)
- In the following query, the projection `{ "grades.$": 1 }` returns only the first element greater than or equal to `85` for the `grades` field. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#project-array-values)
- In the following query, the projection `{ "grades.$": 1 }` returns only the first element with the `mean` greater than `70` for the `grades` field: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#project-array-documents)
- Counts documents in a collection or view. Returns a document with the count, `n`, and the command status, `ok`. — [source](https://www.mongodb.com/docs/manual/reference/command/count.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#syntax)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#stable-api-support)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#accuracy-and-sharded-clusters)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#accuracy-and-sharded-clusters)
- [`$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](https://www.mongodb.com/docs/manual/reference/command/count.md#accuracy-and-sharded-clusters)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#accuracy-after-unexpected-shutdown)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#accuracy-after-unexpected-shutdown)
- The following operation counts all documents in the `orders` collection: — [source](https://www.mongodb.com/docs/manual/reference/command/count.md#count-all-documents)
- The following operation counts documents in the `orders` collection where the `ord_dt` field is greater than `Date('01/01/2012')`: — [source](https://www.mongodb.com/docs/manual/reference/command/count.md#count-documents-that-match-a-query)
- 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](https://www.mongodb.com/docs/manual/reference/command/count.md#skip-documents-in-count)
- Counts and returns the total number of items in an array. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/size.md#definition)
- { $sample: { size: <positive integer N> } } — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- [ { $sample: { size: 3 } } ] — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- const pipeline = [{ $sample: { size: 5 } }]; — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- const cursor = collection.aggregate(pipeline); — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/)
- | Example | Results | | --- | --- | | `{ $in: [ 2, [ 1, 2, 3 ] ] }` | `true` | | `{ $in: [ "abc", [ "xyz", "abc" ] ] }` | `true` | | `{ $in: [ "xy", [ "xyz", "abc" ] ] }` | `false` | | `{ $in: [ [ "a" ], [ "a" ] ] }` | `false` | | `{ $in: [ [ "a" ], [ [ "a" ] ] ] }` | `true` | | `{ $in: [ /^a/, [ "a" ] ] }` | `false` | | `{ $in: [ /^a/, [ /^a/ ] ] }` | `true` | — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/in.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#definition)
- The [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#syntax)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#syntax)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#sort-consistency)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#return-in-natural-order)
- The [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection operator specifies the number of elements in an array to return in the query result. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#definition)
- The $slice projection operator can only be used within a [find command projection](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#std-label-find-projection). To use $slice anywhere an expression can be used, see the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/slice.md#mongodb-expression-exp.-slice) expression operator. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#definition)
- For information on limiting the size of an array during an update with [`$push`](https://www.mongodb.com/docs/manual/reference/operator/update/push.md#mongodb-update-up.-push), see the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/update/slice.md#mongodb-update-up.-slice) update modifier instead. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#definition)
- The [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) has one of the following syntax forms: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#syntax)
- The [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection by itself is considered an exclusion. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#slice-of-embedded-array)
- In previous versions, the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection also include the other fields in the nested document regardless of whether the projection is an inclusion or an exclusion. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#slice-of-embedded-array)
- In previous versions, the projection applies both projections and returns the first element (`$slice: 1`) in the `instock` array but suppresses the `warehouse` field in the projected element. Starting in MongoDB 4.4, to achieve the same result, use the [`db.collection.aggregate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) method with two separate [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stages. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#path-collision-slice-of-an-array-and-embedded-fields)
- The following operation uses the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection operator on the `comments` array to return the array with its first three elements. If the array has less than three elements, all elements in the array are returned. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#return-an-array-with-its-first-3-elements)
- The following operation uses the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection operator on the `comments` array to return the array with its last three elements. If the array has less than three elements, all elements in the array are returned. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#return-an-array-with-its-last-3-elements)
- The following operation uses the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection operator on the `comments` array to: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#return-an-array-with-3-elements-after-skipping-the-first-element)
- The following operation uses the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection operator on the `comments` array to — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#return-an-array-with-3-elements-after-skipping-the-last-element)
- ```javascript [ { _id: 0, type: 'pepperoni', size: 'small', price: 19, totalNumber: 10, orderDate: ISODate('2023-03-13T08:14:30.000Z') }, { _id: 5, type: 'cheese', size: 'large', price: 14, totalNumber: 10, orderDate: ISODate('2024-01-12T05:08:13.000Z') }, { _id: 3, type: 'cheese', size: 'small', price: 12, totalNumber: 15, orderDate: ISODate('2023-03-13T11:21:39.736Z') }, { _id: 1, type: 'pepperoni', size: 'medium', price: 20, totalNumber: 20, orderDate: ISODate('2023-03-13T09:13:24.000Z') }, { _id: 2, type: 'pepperoni', size: 'large', price: 21, totalNumber: 30, orderDate: ISODate('2023-03-1 — [source](https://www.mongodb.com/docs/manual/reference/command/setQuerySettings.md#examples)
- Zone sharding does not support time series collections. The balancer always distributes data in sharded time series collections evenly across all shards in the cluster. — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-considerations.md#zone-sharding)
- | Start value | The `nearestAirport` value from the `travelers` collection: `{ ... nearestAirport: "JFK" }` | | --- | --- | | Depth 0 | `{ _id: 0, airport: "JFK", connects: [ "BOS", "ORD" ] }` | | Depth 1 | `{ _id: 1, airport: "BOS", connects: [ "JFK", "PWM" ] } { _id: 2, airport: "ORD", connects: [ "JFK" ] }` | | Depth 2 | `{ _id: 3, airport: "PWM", connects: [ "BOS", "LHR" ] }` | — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphLookup.md#across-multiple-collections)
- The IP address (or hostname) and the ephemeral port of the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) where the operation originates. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- Commit coordination is handled by a shard, and `$currentOp` (run either on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) or a shard member) returns a shard's coordination information only for transactions the shard is currently coordinating. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- The cumulative number of documents returned by the cursor. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- The cumulative number of batches returned by the cursor. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- The field appears only for change stream cursors. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- For non-tailable cursors, the value is always false. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- The `opid` of the operation using the cursor. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentOp.md#output-fields)
- Query the collection using find(). The projection document, { _id: 0 }, suppresses the _id field in the output display. — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- db.keyTypes.find( {}, { _id: 0 } ) — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- db.keyTypes.find( {}, { _id: 0 } ).sort( { seqNum: 1} ) — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- db.keyTypes.find( {}, { _id: 0 } ).sort( { seqType: 1} ) — [source](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/)
- The [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) stage has the following prototype form: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#definition)
- [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) takes a positive integer that specifies the maximum number of documents to skip. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#definition)
- This operation skips the first 5 documents passed to it by the pipeline. [`$skip`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-pipeline-pipe.-skip) has no effect on the content of the documents it passes along the pipeline. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip.md#mongodb-shell)
- This page describes the `$count` aggregation pipeline stage. You can also use `$count` in these other contexts: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#definition)
- - [`$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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#definition)
- - [`$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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#definition)
- You can use `$count` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#compatibility)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#behavior)
- If the input dataset is empty, `$count` doesn't return a result. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#mongodb-shell)
- 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](https://www.mongodb.com/docs/manual/reference/database-profiler/)
- "getMore" : Long("19234103609"), — [source](https://www.mongodb.com/docs/manual/reference/database-profiler/)
- The ID of the cursor accessed by a query and getmore operations. — [source](https://www.mongodb.com/docs/manual/reference/database-profiler/)
- The system.profile collection includes metrics for the getMore operation. In this example, getMore returns additional documents from the test.report collection. — [source](https://www.mongodb.com/docs/manual/reference/database-profiler/)
- "getMore" : Long("33629063128"), — [source](https://www.mongodb.com/docs/manual/reference/database-profiler/)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#latencystats-document)
- The `count` field only exists in the output if you specify the `count` option. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#count-field)
- The count is based on the collection's metadata, which provides a fast but sometimes inaccurate count for sharded clusters. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#count-field)
- If you run `$collStats` with the `count: {}` option on a `matrices` collection: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#count)
- For example, if you run `$collStats` on a sharded collection with the `count: {}` option on a collection named `matrices`: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#collstats-on-sharded-collections)
- ```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](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/group-and-total.md#steps)
- ```cpp auto cursor = orders.aggregate(pipeline); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/group-and-total.md#steps)
- ```php $cursor = $orders->aggregate($pipeline); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/group-and-total.md#steps)
- ```go pipeline := mongo.Pipeline{ matchStage, sortStageOrderDate, groupStage, sortStageFirstPurchaseDate, setStage, unsetStage, } cursor, err := orders.Aggregate(ctx, pipeline) — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/group-and-total.md#steps)
- ```rust let mut cursor = orders.aggregate(pipeline).await?; ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/group-and-total.md#steps)
- - Filters results to return only documents matching the specified case. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#case-sensitivity-process)
- - Filters results to return only documents matching the diacritic marks in the specified terms. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#diacritic-sensitivity-process)
- Regardless of the ordering of the fields in the document, the [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) projection of an existing field returns the field after the other existing field inclusions. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#field-order)
- The following projection returns the `games` field after the other existing fields included in the projection even though in the document, the field is listed before `joined` and `lastLogin` fields: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#field-order)
- The examples on the [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) projection operator assumes a collection `schools` with the following documents: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#examples)
- The following [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) operation queries for all documents where the value of the `zipcode` field is `"63109"`. The [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) projection returns only the **first** matching element of the `students` array where the `school` field has a value of `102`: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#zipcode-search)
- The following code example finds all documents in which the value of the `Zipcode` field is `"63109"`. For each matching document, the projection returns the following fields: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#zipcode-search)
- The operation returns the following documents that have a `zipcode` value of `"63109"` and projects the `students` array using [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch): The operation returns the following documents that have a `zipcode` value of `"63109"` and projects the `students` array using [`$elemMatch`:](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#zipcode-search)
- The [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch) projection can specify criteria on multiple fields. — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- The following [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) operation queries for all documents where the value of the `zipcode` field is `"63109"`. The projection includes the **first** matching element of the `students` array where the `school` field has a value of `102` **and** the `age` field is greater than `10`: — [source](https://www.mongodb.com/docs/manual/reference/operator/projection/elemMatch.md#elemmatch-https-www-mongodb-com-docs-manual-reference-operator-projection-elemmatch-md-mongodb-projection-proj-elemmatch-with-multiple-fields)
- 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](https://www.mongodb.com/docs/manual/reference/command/getMore.md#output)
- 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](https://www.mongodb.com/docs/manual/reference/command/getMore.md#access-control)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.collation.md#definition)
- The [`cursor.collation()`](https://www.mongodb.com/docs/manual/reference/method/cursor.collation.md#mongodb-method-cursor.collation) accepts the following collation document: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.collation.md#definition)
- The `$count` accumulator is available in these stages: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#definition)
- - [`$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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#definition)
- The `$count` accumulator does not accept any parameters. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#syntax)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#syntax)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#examples)
- - `$count: {}` sets the `countNumberOfMoviesForGenre` field to the number of movies that share the same genre. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count-accumulator.md#examples)
- - The `similarity_top_k` parameter to return only the three most relevant documents. — [source](https://www.mongodb.com/docs/atlas/ai-integrations/llamaindex.md#basic-semantic-search)
- 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](https://www.mongodb.com/docs/atlas/performance-advisor.md#access-performance-advisor-with-the-mcp-server)
- On [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), you can set `profile` level to: — [source](https://www.mongodb.com/docs/manual/reference/command/profile.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- - [`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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#use-tsincrement-in-a-change-stream-cursor-to-monitor-collection-changes)
- Available tabs: other tabs: standalone, repl-set, mongos --> — [source](https://www.mongodb.com/docs/manual/reference/method/db.setProfilingLevel.md)
- The following example sets for a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance: — [source](https://www.mongodb.com/docs/manual/reference/method/db.setProfilingLevel.md#disable-profiler-and-set-slow-operation-threshold-and-sample-rate)
- - the `--setParameter` command-line option for [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--setParameter) and [`mongos`:](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-option-mongos.--setParameter) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#synopsis)
- ```bash mongod --setParameter <parameter>=<value> mongos --setParameter <parameter>=<value> ``` — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#synopsis)
- For additional configuration options, see [Self-Managed Configuration File Options](https://www.mongodb.com/docs/manual/reference/configuration-options.md#std-label-configuration-options), [`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) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#synopsis)
- Starting in MongoDB 8.3, if [`mongod --tlsFIPSMode`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--tlsFIPSMode) or [`mongos --tlsFIPSMode`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-option-mongos.--tlsFIPSMode) is enabled, `SCRAM-SHA-1` is excluded from the effective default. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#authentication-parameters)
- If not set, mongod or mongos does not attempt to bind to the LDAP server. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#authentication-parameters)
- [`saslHostName`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.saslHostName) does not affect the hostname of the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance for any purpose beyond the configuration of SASL and Kerberos. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#oidcidentityproviders-fields)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#oidcidentityproviders-fields)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#oidcidentityproviders-fields)
- The maximum number of seconds the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) / [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance should wait to receive the OCSP status response for its certificates. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#oidcidentityproviders-fields)
- On a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance, specifies the interval (in seconds) at which the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance checks to determine whether the in-memory cache of [user objects](https://www.mongodb.com/docs/manual/reference/system-users-collection.md) has stale data, and if so, clears the cache. If there are no changes to user objects, [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mon — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#oidcidentityproviders-fields)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- Maximum number of times the server retries an operation for internal server-side client connections, such as [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) and [`mongod`.](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-program-mongod) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- Enables support for outbound TCP Fast Open (TFO) connections from the `mongod/mongos` to a client. TFO requires both the client and the `mongod/mongos` host machine support and enable TFO. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- Enables support for accepting inbound TCP Fast Open (TFO) connections to the `mongod/mongos` from a client. TFO requires both the client and `mongod/mongos` host machine support and enable TFO: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#general-parameters)
- For [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), the diagnostic data files, by default, are stored in a directory under the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance's `--logpath` or [`systemLog.path`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-systemLog.path) directory. The diagnostic data directory is computed by truncating the logpath's file extension(s) and concatenating `diagnostic.data` to the remaining name. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#diagnostic-parameters)
- For example, if [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) has `--logpath /var/log/mongodb/mongos.log.201708015`, then the diagnostic data directory is `/var/log/mongodb/mongos.diagnostic.data/` directory. To specify a different diagnostic data directory for [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), set the [`diagnosticDataCollectionDirectoryPath`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.diagnosticDataCollectionDirectoryPath) parame — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#diagnostic-parameters)
- Specify the directory for the diagnostic directory for [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos). If the directory does not exist, [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) creates the directory. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#diagnostic-parameters)
- If unspecified, the diagnostic data directory is computed by truncating the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance's `--logpath` or [`systemLog.path`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-systemLog.path) file extension(s) and concatenating `diagnostic.data`. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#diagnostic-parameters)
- For example, if [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) has `--logpath /var/log/mongodb/mongos.log.201708015`, then the diagnostic data directory is `/var/log/mongodb/mongos.diagnostic.data/`. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#diagnostic-parameters)
- - 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](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- 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](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- This parameter mitigates excessive CPU use from unauthenticated clients that send streaming `hello` commands with very small `maxAwaitTimeMS` values. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- *Default*: `{ samplingRate: 0.01, maxTimeMS: 1000 }` — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- Sets the maximum oplog application batch size in bytes. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#replication-and-consistency)
- Without this setting enabled, the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) only loads a routing table as needed for incoming client connections, and only loads the specific routing table for the namespace of a given request. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- Specifies the time (in milliseconds) to wait for any ongoing database operations to complete before initiating a shutdown of [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) in response to a `SIGTERM` signal. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- Or if using the [`setParameter`](https://www.mongodb.com/docs/manual/reference/command/setparameter.md#mongodb-dbcommand-dbcmd.setParameter) command in a [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) session that is connected to a running [`mongos`:](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- The `persistedChunkCacheUpdateMaxBatchSize` parameter specifies the maximum batch size used for updating the persisted chunk cache. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- Interval that a sampler (`mongos` or `mongod`) refreshes its query analyzer sample rates. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- The sample rate configured by the `configureQueryAnalyzer` command is divided among `mongos` instances in the sharded cluster or `mongod` instances in the replica set based on the traffic going through them. To make the sample rate assignment for a `mongos` or `mongod` more responsive to the traffic going through it, decrease this value. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- This example sets `queryAnalysisSamplerConfigurationRefreshSecs` to 60 seconds at startup on a `mongos` instance: — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- Maximum time that [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) goes without communication to a host before [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) drops all connections to the host. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- Maximum number of simultaneous initiating connections (including pending connections in setup/refresh state) each TaskExecutor connection pool can have to a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instance. You can set this parameter to control the rate at which [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) adds connections to a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instance. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- - On-prem deployments: `32767` for both [`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) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) can have up to `n` TaskExecutor connection pools, where `n` is the number of cores. See [`taskExecutorPoolSize`.](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.taskExecutorPoolSize) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- For a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) using the [`warmMinConnectionsInShardingTaskExecutorPoolOnStartup`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.warmMinConnectionsInShardingTaskExecutorPoolOnStartup) parameter, the `ShardingTaskExecutorPoolMinSize` parameter also controls how many connections to each shard host are established on startup of the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance before it begins accepting — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- Maximum time the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) waits before attempting to heartbeat an idle connection in the pool. An idle connection may be discarded during the refresh if the pool is above its [minimum size.](https://www.mongodb.com/docs/manual/reference/parameters.md#std-label-sharding-pool-minsize-parameters) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- Maximum time the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) waits for a heartbeat before timing out the heartbeat. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- For example, if `mongos` retries an operation that was previously load shed by the shard, it uses a token in the retry. If the attempt succeeds, it returns the token to the shard plus the [`shardRetryTokenReturnRate`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.shardRetryTokenReturnRate). If the attempt fails, it tries again with a new token. If it finds the bucket empty, it doesn't retry the operation. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- The number of Task Executor connection pools to use for a given [`mongos`.](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#sharding-parameters)
- A timeout for this behavior can be configured with the [`warmMinConnectionsInShardingTaskExecutorPoolOnStartupWaitMS`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.warmMinConnectionsInShardingTaskExecutorPoolOnStartupWaitMS) parameter. If this timeout is reached, the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) will begin accepting client connections regardless of the size of its connection pool. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#error-response)
- [Progress Monitor](https://www.mongodb.com/docs/manual/administration/health-managers.md#std-label-health-managers-progress-monitor) runs tests to ensure that Health Manager checks do not become stuck or unresponsive. Progress Monitor runs these tests in intervals specified by `interval`. If a health check begins but does not complete within the timeout given by `deadline`, Progress Monitor stops the [mongos](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) and removes it from the cluster. — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#health-managers)
- | Field | Description | Units | | --- | --- | --- | | `interval` | How often to ensure Health Managers are not stuck or unresponsive. | Milliseconds | | `deadline` | Timeout before automatically failing the [mongos](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) if a Health Manager check is not making progress. | Seconds | — [source](https://www.mongodb.com/docs/manual/reference/parameters.md#progressmonitor-fields)
- var metaFieldResults = stocks.Find(query) .Project(Builders<Stocks>.Projection.Exclude("_id")) .ToEnumerable(); — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-quick-start.md)
- FindIterable<Document> metaFieldResults = stocks.find(query) .projection(new Document("_id", 0)); — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-quick-start.md)
- ```javascript const metafieldResults = await stocks.find( { ticker: 'MDB' }, { projection: { _id: 0 } } ); — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-quick-start.md)
- const timefieldResults = await stocks.find(query, { projection: { _id: 0 }, }); — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-quick-start.md)
- | 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#syntax)
- The following diagram shows an example `distinct()` call. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#syntax)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#array-fields)
- - 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#transactions)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#client-disconnection)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.distinct.md#return-distinct-values-for-an-array-field)
- The [`cursor.hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) method has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#definition)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listSampledQueries.md#read-queries)
- { _id: 0, type: "pepperoni", size: "small", price: 19, — [source](https://www.mongodb.com/docs/manual/core/query-shapes/)
- db.collection.countDocuments() (mongosh method) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- The query selection criteria. To count all documents, specify an empty document. See also Query Restrictions. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- Optional. Extra options that affects the count behavior. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- Optional. The maximum number of documents to count. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- Optional. The maximum amount of time to allow the count to run. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- countDocuments() can be used inside distributed transactions. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- db.movies.countDocuments( { directors: "David Lynch" } ) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- db.collection.estimatedDocumentCount() — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- collStats pipeline stage with the count option — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- db.collection.estimatedDocumentCount — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- The [`pretty()`](https://www.mongodb.com/docs/manual/reference/method/cursor.pretty.md#mongodb-method-cursor.pretty) method has the following prototype form: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.pretty.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.pretty.md#examples)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.maxAwaitTimeMS.md#definition)
- The [`maxAwaitTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxawaittimems.md#mongodb-method-cursor.maxAwaitTimeMS) method has the following prototype form: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.maxAwaitTimeMS.md#definition)
- The [`maxAwaitTimeMS()`](https://www.mongodb.com/docs/manual/reference/method/cursor.maxawaittimems.md#mongodb-method-cursor.maxAwaitTimeMS) method has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.maxAwaitTimeMS.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.maxAwaitTimeMS.md#example)
- Connect [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) to a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance in the sharded cluster and re-enable the migration with [`setAllowMigrations`:](https://www.mongodb.com/docs/manual/reference/command/setallowmigrations.md#mongodb-dbcommand-dbcmd.setAllowMigrations) — [source](https://www.mongodb.com/docs/manual/tutorial/build-indexes-on-sharded-clusters.md#e-enable-migrations)
- The [`min()`](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#mongodb-method-cursor.min) method has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.min.md#example)
- - The [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) expression can be present in either an inclusion or an exclusion projection. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#usage-in-projection)
- - In aggregation, if you include the [`{ $meta: "textScore" }`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) expression in both the projection and sort, the projection and sort can have different field names for the expression. The field name in the sort is disregarded by the query system. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#sort-with-projection)
- The following query performs a text search for the term `cake` and uses the [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) operator in the projection document to include the score assigned to each matching document: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#meta-textscore)
- For additional examples of `"textScore"` projections and sorts, see [Relevance Score Examples.](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#std-label-ex-text-search-score) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#meta-textscore)
- ```javascript [ { _id: 0, allowedRoles: [ 'Marketing' ], comment: 'For marketing team', yearlyBudget: 15000 }, { _id: 2, allowedRoles: [ 'Operations' ], comment: 'For operations team', yearlyBudget: 19000, cloudBudget: 12000 }, { _id: 3, allowedRoles: [ 'Development' ], comment: 'For development team', yearlyBudget: 27000 } ] ``` — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setIntersection.md#retrieve-documents-for-roles-granted-to-the-current-user)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample.md#random-sort-behavior)
- This tutorial demonstrates how to access documents in a [cursor.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-cursor) — [source](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md)
- - Save a cursor as a variable using the `let` keyword. — [source](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#about-this-task)
- - 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#about-this-task)
- - 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#about-this-task)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#batch-sizes)
- You can call the cursor variable in the shell to print matching documents. — [source](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#save-a-cursor-with-let)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#access-documents-in-a-cursor-with-next-https-www-mongodb-com-docs-manual-reference-method-cursor-next-md-mongodb-method-cursor-next)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#access-documents-in-a-cursor-with-hasnext-https-www-mongodb-com-docs-manual-reference-method-cursor-hasnext-md-mongodb-method-cursor-hasnext)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#access-documents-in-a-cursor-with-hasnext-https-www-mongodb-com-docs-manual-reference-method-cursor-hasnext-md-mongodb-method-cursor-hasnext)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#access-documents-in-a-cursor-with-foreach-https-www-mongodb-com-docs-manual-reference-method-cursor-foreach-md-mongodb-method-cursor-foreach)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#access-documents-in-a-cursor-with-foreach-https-www-mongodb-com-docs-manual-reference-method-cursor-foreach-md-mongodb-method-cursor-foreach)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#access-documents-in-a-cursor-with-foreach-https-www-mongodb-com-docs-manual-reference-method-cursor-foreach-md-mongodb-method-cursor-foreach)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#access-documents-in-a-cursor-with-toarray-https-www-mongodb-com-docs-manual-reference-method-cursor-toarray-md-mongodb-method-cursor-toarray)
- 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](https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor.md#access-documents-in-a-cursor-with-toarray-https-www-mongodb-com-docs-manual-reference-method-cursor-toarray-md-mongodb-method-cursor-toarray)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.hasNext.md)
- In mongosh, this command can also be run through the db.collection.distinct() helper method. — [source](https://www.mongodb.com/docs/manual/reference/command/distinct/)
- For the equivalent mongosh method, see db.collection.distinct(). For driver-specific wrapper methods, see the driver documentation. — [source](https://www.mongodb.com/docs/manual/reference/command/distinct/)
- 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](https://www.mongodb.com/docs/manual/reference/command/distinct/)
- { _id: 0, temperatures: [ { value: 1 }, { value: 4 } ] }, — [source](https://www.mongodb.com/docs/manual/reference/command/distinct/)
- - 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](https://www.mongodb.com/docs/manual/core/views/join-collections-with-view.md#create-a-joined-view)
- cursor.disableBlockWarnings — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.allowDiskUse/)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.showRecordId.md#example)
- 2. Enter the projection document into the Project field. — [source](https://www.mongodb.com/docs/compass/query/project.md)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.readPref.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.readPref.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#perform-a-count)
- - 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](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-compound/sort-order.md#learn-more)
- ```csharp .Project(Builders<Order>.Projection .Exclude(o => o.Id) .Exclude(o => o.ProductName) .Exclude(o => o.ProductVariation)); — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- 3) Add a projection stage to remove unneeded fields. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```csharp .Project(Builders<BsonDocument>.Projection .Exclude("_id") .Exclude("Description") ); — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.next.md)
- - 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](https://www.mongodb.com/docs/compass/query-with-natural-language/prompt-natural-language-aggregation.md#about-this-task)
- 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](https://www.mongodb.com/docs/compass/query-with-natural-language/prompt-natural-language-aggregation.md#steps)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/changeStream.md#definition)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents/specify-query-timeout.md)
- - 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](https://www.mongodb.com/docs/manual/tutorial/query-documents/specify-query-timeout.md#specify-a-time-limit-for-queries)
- The optimizer breaks up the `$match` stage into four individual filters, one for each key in the `$match` query document. The optimizer then moves each filter before as many projection stages as possible, creating new `$match` stages as needed. — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#project-or-unset-or-addfields-or-set-match-sequence-optimization)
- **Note: Sequence Optimization with $skip** — [source](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#sort-limit-coalescence)
- - The [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) and [`findAndModify()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.findandmodify.md#mongodb-method-db.collection.findAndModify) projection can accept [aggregation expressions and syntax.](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#projection)
- The `projection` parameter takes a document in the following form: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#projection)
- | Projection | Description | | --- | --- | | `<field>: <1 or true>` | Specifies the inclusion of a field. If you specify a non-zero integer for the projection value, the operation treats the value as `true`. | | `<field>: <0 or false>` | Specifies the exclusion of a field. | | `"<field>.$": <1 or true>` | Uses the [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) array projection operator to return the first element that matches the query condition on the array field. If you specify a non-zero integer for the projection value, the — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#projection)
- The `_id` field is included in the returned documents by default unless you explicitly specify `_id: 0` in the projection to suppress the field. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#id-field-projection)
- - In projections that *explicitly include* fields, the `_id` field is the only field that you can *explicitly exclude*. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#inclusion-or-exclusion)
- - In projections that *explicitly excludes* fields, the `_id` field is the only field that you can *explicitly include*; however, the `_id` field is included by default. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#inclusion-or-exclusion)
- - You must run on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos). Do not issue the operation directly on the shard. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#shard-key-modification)
- The following operation uses projection to only display the `_id`, `points`, and `assignment` fields in the returned document: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#project-the-returned-document)
- The operation returns the *original* document with only the fields specified in the `projection` document and the `_id` field as it was not explicitly suppressed (`_id: 0`) in the [projection document.](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#std-label-projections) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#project-the-returned-document)
- - For a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance, see [`security.javascriptEnabled`](https://www.mongodb.com/docs/manual/reference/configuration-options.md#mongodb-setting-security.javascriptEnabled) configuration option or the [`--noscripting`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-option-mongos.--noscripting) command-line option. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#javascript-enablement)
- Available tabs: other tabs: shard, mongos, mongod --> — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md)
- The output fields vary depending on the version of MongoDB, underlying operating system platform, the storage engine, and the kind of node, including [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [replica set](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-replica-set) member. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#output)
- A document that reports statistics on collection usage via collection counts. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#catalogstats)
- The number of incoming connections from clients to the database server. This includes connections from the current shell session and from other servers, such as [replica set](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-replica-set) members and [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances. Consider the value of [`connections.available`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.connections.available) for additional context. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#connections)
- Count of **all** incoming connections created to the server. This number includes connections that have since closed. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#connections)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#extra-info)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#fle)
- Counts of Queryable Encryption operations. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#fle)
- *Available on both mongod and mongos.* — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#ftdccollectionmetrics)
- Counts how many times this lock runs in write mode, blocking other threads until the write finishes. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#lockcontentionmetrics)
- The number of all active local sessions cached in memory by the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance since the last refresh period. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#logicalsessionrecordcache)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#logicalsessionrecordcache)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- - Open a change stream cursor. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The histogram is only incremented for commands that set a `maxTimeMS` value. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The cumulative number of batches returned by all change stream cursors. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The cumulative amount, in bytes, of oplog scanned by all change stream cursors. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The cumulative amount, in bytes, returned by all change stream cursors. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The cumulative number of oplog entries scanned by all change stream cursors. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The cumulative number of change stream events returned by all change stream cursors. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of open change stream cursors that are pinned. A pinned cursor is one that an operation is actively using. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- A document that reports the number of errors encountered by change stream cursors, categorized by whether the errors are retriable. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of times a replica set state change, such as a primary stepping down, interrupted a change stream cursor. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- [`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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- [`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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- This number can be quite large, as MongoDB will wait for more data even if the `getmore` operation does not initial return data. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- - The `getmore` times out waiting for more data, or — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of cursors with a lifespan >= 10 minutes. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of cursors with a lifespan >= 1 minute to \< 10 minutes. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of cursors with a lifespan >= 5 seconds to \< 15 seconds. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of cursors with a lifespan >= 30 seconds to \< 1 minute. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of cursors with a lifespan \< 1 second. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of cursors with a lifespan >= 15 seconds to \< 30 seconds. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of cursors with a lifespan >= 1 second to \< 5 seconds. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- The number of "pinned" open cursors. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#metrics)
- A document that reports data on MongoDB's network use. These statistics measure ingress and egress connections, specifically the traffic seen by the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) over network connections initiated by clients or other [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-b — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- Reports data on the traffic from egress connections initiated by this `mongod` or `mongos` instance. In most cases, the egress connections are `mongos` communicating with `mongod` for sharding, or `mongod` communicating with `mongod` for replication. It is also possible that `mongod` or `mongos` are communicating with external services, such as `mongot`. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- The total number of physical bytes that `mongod` or `mongos` instances has *received* over network connections that they have initiated to other nodes/services. Physical bytes are the number of bytes that actually reside on disk. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- The total number of physical bytes that `mongod` or `mongos` instances have *sent* over network connections that they have initiated to other nodes/services. Physical bytes are the number of bytes that actually reside on disk. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- The total number of distinct requests that `mongod` or `mongos` have sent and received responses to. Use this value to provide context for the [`network.egress.bytesIn`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.network.egress.bytesIn) and [`network.egress.bytesOut`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.network.egress.bytesOut) values to ensure that MongoDB's network utilization is consistent with expectations and application use. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- The total number of physical bytes that the server has *received* over network connections initiated by clients or other `mongod` or `mongos` instances. Physical bytes are the number of bytes that actually reside on disk. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- The total number of physical bytes that the server has *sent* over network connections initiated by clients or other `mongod` or `mongos` instances. Physical bytes are the number of bytes that actually reside on disk. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- The total number of accepted incoming TCP Fast Open (TFO) connections to the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) since the `mongod` or `mongos` last started. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#network)
- Starting in MongoDB 6.2, the [`opLatencies`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.opLatencies) metric reports for 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) instances. Latencies reported by `mongos` include operation latency time and communication time between the `mongod` and `mongos` instances. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#oplatencies)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#opwriteconcerncounters)
- | 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#opwriteconcerncounters)
- | 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#opwriteconcerncounters)
- | 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#opwriteconcerncounters)
- [`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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#opcounters)
- The cumulative count of operations that are heuristically deprioritized during the server's lifetime. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#queues)
- Document with configuration counts and usage for query settings. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#querysettings)
- Starting in MongoDB 9.0, user-initiated operations that run through [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) only increment `external` counters. In previous releases, these operations only incremented `internal` counters. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#readpreferencecounters)
- A document that reports on the number of times [X.509](https://www.mongodb.com/docs/manual/core/security-x.509.md#std-label-security-auth-x509) has been used to authenticate against the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#security)
- The subject name associated with the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) / [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance's TLS/SSL certificate. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#security)
- The expiration date and time of the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) / [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance's TLS/SSL certificate. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#security)
- A document with data regarding the sharded cluster. The [`lastSeenConfigServerOpTime`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.sharding.lastSeenConfigServerOpTime) is present only for a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) or a shard member, not for a config server. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#sharding)
- The latest optime of the CSRS primary that the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) or the shard member has seen. The optime document includes: — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#sharding)
- The cumulative, always-increasing count of documents that MongoDB clones on the primary node of the recipient shard. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- The cumulative, always-increasing count of documents that MongoDB clones on the primary node of the donor shard. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- The cumulative, always-increasing count of documents that MongoDB deletes on the primary node of the donor shard during chunk migration. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- On a sharded cluster with a single shard, you can control this counter by setting the `directConnectionChecksWithSingleShard` parameter to `true`. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- 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](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- | Name | Description | | --- | --- | | `allShards` | A command targeted all shards | | `manyShards` | A command targeted more than one shard | | `oneShard` | A command targeted one shard | | `unsharded` | A command was run on an unsharded collection | — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- Running the [`serverStatus`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-dbcommand-dbcmd.serverStatus) command on [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) provides insight into the CRUD and aggregation operations that run on a sharded cluster. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- Multi-shard operations can either be [scatter-gather](https://www.mongodb.com/docs/manual/core/sharding-choose-a-shard-key.md#std-label-sharding-query-patterns) or shard specific. Multi-shard scatter-gather operations can [consume more resources](https://www.mongodb.com/docs/manual/core/sharding-troubleshooting-shard-keys.md#std-label-sharding-troubleshooting-scatter-gather). By using the [`shardingStatistics.numHostsTargeted`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.shardingStatistics.numHostsTargeted) metrics you can tune the ag — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#shard)
- For the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), the total number of transactions aborted through this instance since its last startup. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#mongod)
- For the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), the total number of transactions committed through this instance since its last startup. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#mongod)
- For the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), the total number of transactions started on this instance since its last startup. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#mongod)
- *Available on mongos only.* — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#mongod)
- The total number of shards contacted for all transactions started through this [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) since its last startup. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#mongod)
- Total number of shards involved in the commit for all transactions started through this [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) since its last startup. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#mongod)
- | Type | Description | | --- | --- | | `noShards` | Commits of transactions that did not contact any shards. | | `singleShard` | Commits of transactions that affected a single shard. | | `singleWriteShard` | Commits of transactions that contacted multiple shards but whose write operations only affected a single shard. | | `readOnly` | Commits of transactions that only involved read operations. | | `twoPhaseCommit` | Commits of transactions that included writes to multiple shards | | `recoverWithToken` | Commits that recovered the outcome of transactions from another instance or after this inst — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#mongod)
- The cumulative number of TLS \<version> connections that have been made to this [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance. The value is reset upon restart. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#transportsecurity)
- A document that returns statistics on WiredTiger cursor. — [source](https://www.mongodb.com/docs/manual/reference/command/serverStatus.md#wiredtiger)
- MongoDB Atlas limits concurrent incoming connections based on the cluster tier and [class](https://www.mongodb.com/docs/atlas/customize-storage.md#std-label-storage-class-ui). MongoDB Atlas connection limits apply per node. For sharded clusters, MongoDB Atlas connection limits apply per [mongos](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#std-label-sharding-read-operations) router. The number of [mongos](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#std-label-sharding-read-operations) routers is equal to the number of replica set nodes ac — [source](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-atlas-connection-limits-and-cluster-tier)
- - If you only target one shard, you can use a partial shard key in the query specification or, — [source](https://www.mongodb.com/docs/manual/reference/limits.md#sharding-operational-restrictions)
- 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](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- - 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](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- In previous versions, MongoDB treats the inclusion/exclusion of the empty field as it would the projection of non-existing fields. — [source](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- - If the projection of the embedded document comes after any and all projections of its fields, MongoDB projects the embedded document. For example, the projection document `{ "size.uom": 1, size: 1 }` produces the same result as the projection document `{ size: 1 }`. — [source](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- - If the projection of the embedded document comes before the projection any of its fields, MongoDB projects the specified field or fields. For example, the projection document `{ "size.uom": 1, size: 1, "size.h": 1 }` produces the same result as the projection document `{ "size.uom": 1, "size.h": 1 }`. — [source](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- Path Collision: `$slice` of an Array and Embedded Fields — [source](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- `$` Positional Operator and `$slice` Restriction — [source](https://www.mongodb.com/docs/manual/reference/limits.md#operations)
- 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](https://www.mongodb.com/docs/manual/reference/limits.md#sessions)
- 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](https://www.mongodb.com/docs/manual/reference/limits.md#sessions)
- 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](https://www.mongodb.com/docs/manual/reference/limits.md#sessions)
- Both `mongod` and [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances default to `snappy,zstd,zlib` compressors, in that order. — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#core-options)
- - For clients that don't provide certificates, [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) encrypts the TLS/SSL connection, assuming the connection is successfully made. — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#tls-options)
- Returns the count of all documents in a collection or view. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- db.collection.estimatedDocumentCount() does not take a query filter and instead uses metadata to return the count for a collection. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- The document count is calculated by executing the aggregation pipeline in the view definition. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- There is no fast estimated document count. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- On a sharded cluster, the resulting count will not correctly filter out orphaned documents. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- After an unclean shutdown, the count may be incorrect. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- validate updates the count statistic in the collStats output with the latest value. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- If the client that issued db.collection.estimatedDocumentCount() disconnects before the operation completes, MongoDB marks db.collection.estimatedDocumentCount() for termination using killOp. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- db.movies.estimatedDocumentCount({}) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- Iterates the cursor to apply a JavaScript `function` to each document from the cursor. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.forEach.md#definition)
- | 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](https://www.mongodb.com/docs/manual/reference/method/cursor.forEach.md#method-fields)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.forEach.md#learn-more)
- | **Example** | **Metrics** | **Metadata** | | --- | --- | --- | | Stock data | Stock price | Stock ticker, exchange | | Weather data | Temperature | Sensor identifier, location | | Website visitors | View count | URL | — [source](https://www.mongodb.com/docs/manual/core/timeseries-collections.md)
- [`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](https://www.mongodb.com/docs/manual/administration/monitoring.md#mongostat)
- During normal operation, [`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) instances report a live account of all server activity and operations to either standard output or a log file. The following runtime settings control these options. — [source](https://www.mongodb.com/docs/manual/administration/monitoring.md#process-logging)
- You can specify these configuration operations as the command line arguments to [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`.](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) — [source](https://www.mongodb.com/docs/manual/administration/monitoring.md#process-logging)
- 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](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-estimate-storage-impact.md#about-this-task)
- 1. Calculate the worst-case tag count for each field and query type. — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-estimate-storage-impact.md#steps)
- 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](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-estimate-storage-impact.md#steps)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#definition)
- The `projection` parameter determines which fields are returned in the matching documents. The `projection` parameter takes a document of the following form: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#projection)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#cursor-handling)
- - The following operation uses the [`$in`](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#mongodb-query-op.-in) operator to return documents in the [bios collection](https://www.mongodb.com/docs/manual/reference/bios-example-collection.md) where `_id` equals either `5` or `ObjectId("<object-id>")`: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#query-using-operators)
- ```javascript db.bios.find( { _id: { $in: [ 5, ObjectId("<object-id>") ] } } ) ``` — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#query-using-operators)
- ```javascript db.bios.find( { contribs: { $in: [ "ALGOL", "Lisp" ]} } ) ``` — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#query-for-an-array-element)
- Unless the `_id` field is explicitly excluded in the projection document `_id: 0`, the `_id` field is returned. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#projections)
- The `find()` projection can accept [aggregation expressions and syntax.](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#use-aggregation-expression)
- The `find()` method returns a [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) to the results. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#iterate-the-returned-cursor)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#iterate-the-returned-cursor)
- The following example sets the batch size to 3. Future `find()` operations will only return 3 documents per cursor iteration. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#iterate-the-returned-cursor)
- The following example uses the variable `myCursor` to iterate over the cursor and print the matching documents: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#with-variable-name)
- [`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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#modify-the-cursor-behavior)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#order-documents-in-the-result-set)
- [`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](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#order-documents-in-the-result-set)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.isClosed.md)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.isClosed.md)
- - Ensure full bidirectional network connectivity between [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod), [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), and config servers. — [source](https://www.mongodb.com/docs/manual/administration/production-checklist-operations.md#sharding)
- - Adjust the `ulimit` values on your hardware to suit your use case. If multiple [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances are running under the same user, scale the `ulimit` values accordingly. See: [UNIX ulimit Settings for Self-Managed Deployments](https://www.mongodb.com/docs/manual/reference/ulimit.md) for more information. — [source](https://www.mongodb.com/docs/manual/administration/production-checklist-operations.md#linux)
- Adjust `batchSize` to a value appropriate to your database, load, and application needs. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md#definition)
- The [`batchSize()`](https://www.mongodb.com/docs/manual/reference/method/cursor.batchsize.md#mongodb-method-cursor.batchSize) method takes the following field: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize.md#example)
- Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortByCount.md#definition)
- The documents are sorted by `count` in descending order. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortByCount.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortByCount.md#mongodb-shell)
- The following example uses the `projection` field in the query to omit the `_id` field from the results: — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#query-a-time-series-collection)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- - 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](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-procedures.md#run-aggregations-on-a-time-series-collection)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.comment.md#behavior)
- The [`db.killOp()`](https://www.mongodb.com/docs/manual/reference/method/db.killop.md#mongodb-method-db.killOp) method can be run on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) and can kill queries (read operations) that are running on more than one shard in a cluster. — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#kill-read-operations)
- 1. On the **same** [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) where the client issued the query, find the opid of the query operation to kill by running the aggregation pipeline [`$currentOp`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-pipeline-pipe.-currentOp) with the `localOps: true`: — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#from-the-mongos-instance)
- You must issue this aggregation operation on the **same** [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) where the client issued the query. — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#from-the-mongos-instance)
- 2. Once you find the query operation to kill, issue [`db.killOp()`](https://www.mongodb.com/docs/manual/reference/method/db.killop.md#mongodb-method-db.killOp) with the opid on the [`mongos`:](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#from-the-mongos-instance)
- If the write operation is associated with a session, you can use the [`killSessions`](https://www.mongodb.com/docs/manual/reference/command/killsessions.md#mongodb-dbcommand-dbcmd.killSessions) command on the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) to kill the write operation across shards. — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#kill-write-operations)
- 1. Run the aggregation pipeline [`$currentOp`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-pipeline-pipe.-currentOp) on the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) to find the `lsid` (logical session id). — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#kill-write-operations)
- 1. Using the returned `lsid` information, issue the [`killSessions`](https://www.mongodb.com/docs/manual/reference/command/killsessions.md#mongodb-dbcommand-dbcmd.killSessions) command on the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) to kill the operation on the shards. — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#kill-write-operations)
- 1. From a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), run the aggregation pipeline [`$currentOp`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-pipeline-pipe.-currentOp) to find the opid(s) of the query operation on the shards: — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#kill-write-operations)
- 2. Using the opid information, issue [`db.killOp()`](https://www.mongodb.com/docs/manual/reference/method/db.killop.md#mongodb-method-db.killOp) on the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) to kill the operation on the shards. — [source](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#kill-write-operations)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#bucket-by-year-and-filter-by-bucket-results)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#use-bucket-with-facet-to-bucket-by-multiple-fields)
- | Field | Description | | --- | --- | | `count` | Count of documents in the bucket. | | `artwork` | Array of documents containing information on each artwork in the bucket. | — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#use-bucket-with-facet-to-bucket-by-multiple-fields)
- - In `The Comancheros`, the first `genres` element is `Action`. This value is used as the sort key even though it does not match the filter `{ genres: { $in: [ "Drama", "Western" ] } }`. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#filter-and-sort-by-an-array-field)
- The `$project` stage specifies `_id: 0` to suppress the `_id` field from the documents it passes to the next stage. — [source](https://www.mongodb.com/docs/mongodb-shell/run-agg-pipelines.md#example-aggregation-pipeline)
- - [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](https://www.mongodb.com/docs/manual/reference/command/collMod.md#attach-comment)
- $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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- Internal getMore operations increment the execCount metric. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- noCursorTimeout option associated with the key — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- Metrics related to the cursor and batching protocol — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- Counts of the plan shapes that MongoDB selected for queries with the given key. For details, see Plan Shape Counters. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- Counts of the overall shapes of the winning plans. Each winning plan matches at most one pattern. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- Counts of the types of plan stages that appear in the winning plans. A single winning plan can match multiple node counters. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- Counts the overall shape of each winning plan. The patterns are mutually exclusive, so each query execution increments at most one pattern counter. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- Projection stages, counted separately by projection type. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- key.queryShape.projection — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- cursor: { batchSize: '?number' } — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/queryStats/)
- This page provides examples of query operations with projection using the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method in [`mongosh`.](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md)
- If you do not specify a [projection](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-projection) document, the [`db.collection.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) method returns all fields in the matching documents. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-fields-in-matching-documents)
- A projection can explicitly include several fields by setting the `<field>` to `1` in the projection document. The following operation returns all documents that match the query. In the result set, only the `item`, `status` and, by default, the `_id` fields return in the matching documents. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-the-specified-fields-and-the-id-field-only)
- You can remove the `_id` field from the results by setting it to `0` in the projection, as in the following example: — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- You can return specific fields in an embedded document. Use the [dot notation](https://www.mongodb.com/docs/manual/core/document.md#std-label-document-dot-notation) to refer to the embedded field and set to `1` in the projection document. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-specific-fields-in-embedded-documents)
- You can suppress specific fields in an embedded document. Use the [dot notation](https://www.mongodb.com/docs/manual/core/document.md#std-label-document-dot-notation) to refer to the embedded field in the projection document and set to `0`. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- The following example specifies a projection to exclude the `uom` field inside the `size` document. All other fields are returned in the matching documents: — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-specific-fields-in-embedded-documents)
- The following example uses the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection operator to return the last element in the `instock` array: — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- You can specify [aggregation expressions](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) in a query projection. Aggregation expressions let you project new fields and modify the values of existing fields. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- The following example uses MongoDB Shell syntax. For driver examples of projection with aggregation, see your [driver documentation.](https://www.mongodb.com/docs/drivers/) — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- This page provides examples of query operations with projection using the [`pymongo.collection.Collection.find`](https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.find) method in the [PyMongo](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/) Python driver. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- If you do not specify a [projection](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-projection) document, the [`find`](https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.find) method returns all fields in the matching documents. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-fields-in-matching-documents)
- This page provides examples of query operations with projection using the [com.mongodb.client.MongoCollection.find](https://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/client/MongoCollection.html#find--) method in the MongoDB [Java Synchronous Driver.](http://mongodb.github.io/mongo-java-driver/3.4/driver/) — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- If you do not specify a [projection](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-projection), the [com.mongodb.client.MongoCollection.find](https://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/client/MongoCollection.html#find--) method returns all fields in the matching documents. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-fields-in-matching-documents)
- This page provides examples of query operations with projection using the [com.mongodb.reactivestreams.client.MongoCollection.find](http://mongodb.github.io/mongo-java-driver-reactivestreams/1.6/javadoc/com/mongodb/reactivestreams/client/MongoCollection.html#find\(\)) method in the MongoDB [Java Reactive Streams Driver](http://mongodb.github.io/mongo-java-driver-reactivestreams/1.6/). — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- If you do not specify a [projection](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-projection), the [com.mongodb.reactivestreams.client.MongoCollection.find](http://mongodb.github.io/mongo-java-driver-reactivestreams/1.6/javadoc/com/mongodb/reactivestreams/client/MongoCollection.html#find\(org.bson.conversions.Bson\)) method returns all fields in the matching documents. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#return-all-fields-in-matching-documents)
- This page provides examples of query operations with projection using the [Collection.find()](http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#find) method in the [MongoDB Node.js Driver.](http://mongodb.github.io/node-mongodb-native/3.6/) — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- This page provides examples of query operations with projection using the [`MongoDB\\Collection::find()`](https://www.mongodb.com/docs/php-library/upcoming/reference/method/MongoDBCollection-find.md#mongodb-phpmethod-phpmethod.MongoDB-Collection--find--) method in the [MongoDB PHP Library](https://www.mongodb.com/docs/drivers/php-libraries/). — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- This page provides examples of query operations with projection using the [Mongo::Collection#find()](https://www.mongodb.com/docs/ruby-driver/current/api/Mongo/Collection.html#find-instance_method) method in the [MongoDB Ruby Driver.](https://www.mongodb.com/docs/ruby-driver/current/) — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- This page provides examples of query operations with projection using 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 in the [MongoDB Scala Driver](http://mongodb.github.io/mongo-scala-driver/). — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- This page provides examples of query operations with projection using the [MongoCollection.Find()](https://mongodb.github.io/mongo-csharp-driver/2.10/apidocs/html/M_MongoDB_Driver_MongoCollection_1_Find.htm) method in the [MongoDB .NET/C# Driver](https://mongodb.github.io/mongo-csharp-driver/). — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/projection/elemmatch.md#mongodb-projection-proj.-elemMatch), [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice), and [`$`](https://www.mongodb.com/docs/manual/reference/operator/projection/positional.md#mongodb-projection-proj.-) are the *only* operators that you can use to project specific elements to include in the returned array. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- This page provides examples of query operations with projection using [mongoc\_collection\_find\_with\_opts.](https://mongoc.org/libmongoc/current/mongoc_collection_find_with_opts.html) — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- This page provides examples of query operations with projection using the [Collection.Find](https://godoc.org/github.com/mongodb/mongo-go-driver/mongo#Collection.Find) function in the [MongoDB Go Driver](https://github.com/mongodb/mongo-go-driver/). — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- This page provides examples of query operations with projection using the [`motor.motor_asyncio.AsyncIOMotorCollection.find`](https://motor.readthedocs.io/en/stable/api-asyncio/asyncio_motor_collection.html#motor.motor_asyncio.AsyncIOMotorCollection.find) method in the [Motor](https://motor.readthedocs.io/en/stable/) driver. — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- This page provides examples of query operations with projection using [MongoDB Compass.](https://www.mongodb.com/docs/compass/current.md#std-label-compass-index) — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-fields-with-aggregation-expressions)
- ```javascript { item: 1, status: 1, _id: 0 } ``` — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#suppress-id-field)
- ```javascript { item: 1, status: 1, instock: { $slice: -1 } } ``` — [source](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#project-specific-array-elements-in-the-returned-array)
- - 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#definition)
- - 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#cursor-behavior)
- [`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](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#group-by-and-calculate-a-sum)
- For example, the following aggregation operation specifies the *initial* batch size of `0` for the cursor: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#specify-an-initial-batch-size)
- The following aggregation combines the `state` field projection results from the `suppliers` and `warehouse` collections. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionWith.md#duplicate-results)
- The [`max()`](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#mongodb-method-cursor.max) method has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.max.md#parameters)
- Lists the sessions cached in memory by the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listLocalSessions.md#definition)
- From the connected [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) / [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance's in-memory cache of sessions, the following aggregation operation lists all sessions: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listLocalSessions.md#list-all-local-sessions)
- From the connected [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance's in-memory cache, the following aggregation operation lists all the sessions for the specified user `myAppReader@test`: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listLocalSessions.md#list-all-local-sessions-for-the-specified-users)
- From the connected [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) / [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance's in-memory cache, the following aggregation operation lists all sessions for the current user **if** run with access control: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listLocalSessions.md#list-all-local-sessions-for-the-current-user)
- [`$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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listLocalSessions.md#output)
- Executes a query and returns the first batch of results and the cursor id, from which the client can construct a cursor. — [source](https://www.mongodb.com/docs/manual/reference/command/find.md#definition)
- The query projection explicitly excludes _id and includes only the query field. — [source](https://www.mongodb.com/docs/manual/core/index-wildcard/)
- | 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto.md#comparing-different-granularities)
- For more information on using projections, see Project Fields to Return from Query. — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- { "location.address.city": 1, _id: 0 } — [source](https://www.mongodb.com/docs/manual/core/query-optimization/)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/binarySize.md#string-size-calculation)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.toArray.md)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.toArray.md)
- In earlier versions, MongoDB does not allow JavaScript execution on [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#javascript-enabled)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator.md#behavior)
- The following operation uses [projection](https://www.mongodb.com/docs/manual/reference/method/db.collection.findoneandreplace.md#std-label-findOneAndReplace-projection) to only display the `team` field in the returned document: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndReplace.md#project-specific-fields-in-return-document)
- - To indicate a cursor with the default batch size, specify `cursor: {}`. — [source](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#command-fields)
- - To indicate a cursor with a non-default batch size, use `cursor: { batchSize: <num> }`. — [source](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#command-fields)
- The following example aggregates the `movies` collection to calculate the count of each distinct genre: — [source](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#aggregate-data-with-multi-stage-pipeline)
- { _id: 0, title: 1, runtime: 1 } — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- - Use [targeted operations](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#std-label-sharding-mongos-targeted) for workloads that need to scale with the number of shards. — [source](https://www.mongodb.com/docs/manual/administration/production-checklist-development.md#sharding)
- - 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](https://www.mongodb.com/docs/manual/administration/production-checklist-development.md#drivers)
- For more information on using projections, see [Project Fields to Return from Query.](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results.md#std-label-read-operations-projection) — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#project-only-necessary-data)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.close.md#definition)
- The [`close()`](https://www.mongodb.com/docs/manual/reference/method/cursor.close.md#mongodb-method-cursor.close) method has the following prototype form: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.close.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#merge-results-from-multiple-collections)
- Similarly, run the following aggregation pipeline against the `comments` collection to merge the comment counts into the `yearlyStats` collection. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#merge-results-from-multiple-collections)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#merge-results-from-multiple-collections)
- A collection `monthlyCommentTotals` tracks the running count of comments for each month. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-the-pipeline-to-customize-the-merge)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-the-pipeline-to-customize-the-merge)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-the-pipeline-to-customize-the-merge)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-the-pipeline-to-customize-the-merge)
- - This pipeline can directly access the `count` field in the existing document in the collection; i.e. `$count`. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#use-the-pipeline-to-customize-the-merge)
- [`$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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/listSessions.md#output)
- Available tabs: other tabs: query, getmore, update --> — [source](https://www.mongodb.com/docs/manual/reference/database-profiler.md)
- 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](https://www.mongodb.com/docs/manual/reference/database-profiler.md)
- The previous query explicitly checks that both conditions are satisfied: the `price` array must include at least one value from each [`$in`](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#mongodb-query-op.-in) set. For more information, see [Examples.](https://www.mongodb.com/docs/manual/reference/operator/query/and.md#std-label-query-and-examples) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/and.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.returnKey.md#definition)
- `~cursor.tailable()` has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.tailable.md#definition)
- The [cursor](https://www.mongodb.com/docs/manual/core/cursors.md#std-label-cursors) that `~cursor.tailable()` is attached to. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.tailable.md#definition)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.objsLeftInBatch.md)
- The following example silences warnings on a tailable cursor that is stored in a variable called `myTailableCursor`: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.disableBlockWarnings.md#example)
- { _id: 0, title: 1, year: 1 } — [source](https://www.mongodb.com/docs/manual/reference/operator/query/or/)
- The following pipeline unwinds the `genres` array and groups the resulting documents by genre to count the number of movies in each genre: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind.md#group-by-unwound-values)
- | 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](https://www.mongodb.com/docs/manual/reference/command/planCacheListFilters.md#command-fields)
- The projection associated with this filter. Can be an empty document. — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheListFilters.md#output)
- `$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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateDiff.md#no-fractional-units)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateDiff.md#start-of-week)
- // Stage 4: Project only the fields needed for the result { $project: { _id: 0, title: 1, year: 1, directors: 1, runtime: 1 } } ] ) — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- 4) Add a projection stage to remove unneeded fields. — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- ```csharp .Project(Builders<Person>.Projection .Exclude(p => p.Address) .Exclude(p => p.Id) ); — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- ```cpp auto cursor = persons.aggregate(pipeline); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- ```php $cursor = $persons->aggregate($pipeline); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/filtered-subset.md#steps)
- mongod / mongos instances output all log messages in structured JSON format. Log entries are written as a series of key-value pairs, where each key indicates a log message field type, such as "severity", and each corresponding value records the associated logging information for that field type, such as "informational". Previously, log entries were output as plaintext. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- "$in": [0, 1, 2, 3, ... 4999] — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- "$in": [ 0, 1, ..., 376 ] // Values in array omitted for brevity — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- the --logpath option for mongos for file — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- the --syslog option for mongos for syslog — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- You would set these values in the configuration file or on the command line for your mongod or mongos instance. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- On the shard or mongos that merges the results. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- A mongod or mongos running with redactClientLogData redacts any message accompanying a given log event before logging, leaving only metadata, source files, or line numbers related to the event. redactClientLogData prevents potentially sensitive information from entering the system log at the cost of diagnostic detail. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- 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](https://www.mongodb.com/docs/manual/reference/log-messages/)
- Cache refresh log fields are specific to sharded clusters and only appear in logs generated by the mongos router. They are not available in unsharded replica sets or standalone deployments. — [source](https://www.mongodb.com/docs/manual/reference/log-messages/)
- - Operation Count for all operation types — [source](https://www.mongodb.com/docs/atlas/namespace-insights.md#edit-columns)
- - 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/stdDevPop.md#example)
- For the find command projection operator, see the [`$slice`](https://www.mongodb.com/docs/manual/reference/operator/projection/slice.md#mongodb-projection-proj.-slice) projection operator instead. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/slice.md#definition)
- | Example | Results | | --- | --- | | `{ $slice: [ [ 1, 2, 3 ], 1, 1 ] }` | `[ 2 ]` | | `{ $slice: [ [ 1, 2, 3 ], -2 ] }` | `[ 2, 3 ]` | | `{ $slice: [ [ 1, 2, 3 ], 15, 2 ] }` | `[ ]` | | `{ $slice: [ [ 1, 2, 3 ], -15, 2 ] }` | `[ 1, 2 ]` | — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/slice.md#behavior)
- MongoDB mongos instances route queries and write operations to shards in a sharded cluster. mongos provides the only interface to a sharded cluster from the perspective of applications. Applications never connect or communicate directly with the shards. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- The mongos tracks what data is on which shard by caching the metadata from the config servers. The mongos uses the metadata to route operations from applications and clients to the mongod instances. A mongos has no persistent state and consumes minimal system resources. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- The most common practice is to run mongos instances on the same systems as your application servers, but you can maintain mongos instances on the shards or on other dedicated resources. See also Number of mongos and Distribution. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Establishing a cursor on all targeted shards. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- The mongos then merges the data from each of the targeted shards and returns the result document. Certain query modifiers, such as sorting, are performed on each shard before mongos retrieves the results. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Aggregation operations running on multiple shards may route results back to the mongos to merge results if they don't need to run on the database's primary shard. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- There are two cases in which a pipeline is ineligible to run on mongos. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Generally, the fastest queries in a sharded environment are those that mongos route to a single shard, using the shard key and the cluster meta data from the config server. These targeted operations use the shard key value to locate the shard or subset of shards that satisfy the query document. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- mongos instances broadcast queries to all shards for the collection unless the mongos can determine which shard or subset of shards stores this data. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Multi-update operations are always broadcast operations. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- The updateMany() and deleteMany() methods are broadcast operations, unless the query document specifies the shard key in full. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- mongos can route queries that include the shard key or the prefix of a compound shard key a specific shard or set of shards. mongos uses the shard key value to locate the chunk whose range includes the shard key value and directs the query at the shard containing that chunk. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Depending on the distribution of data in the cluster and the selectivity of the query, mongos may still perform a broadcast operation to fulfill these queries. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- Starting in MongoDB 4.2, MongoDB adds the parameter ShardingTaskExecutorPoolReplicaSetMatching. This parameter determines the minimum size of the mongod / mongos instance's connection pool to each member of the sharded cluster. This value can vary during runtime. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- mongod and mongos maintain connection pools to each replica set secondary for every replica set in the sharded cluster. By default, these pools have a number of connections that is at least the number of connections to the primary. — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/)
- This aggregation stage is only available on [`mongos`.](https://www.mongodb.com/docs/manual/reference/program/mongos.md#std-program-mongos) — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/shardedDataDistribution.md#definition)
- | Parameter | Type | Description | | --- | --- | --- | | options | document | Optional. Extra options that affect the count behavior. | — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount.md#parameters)
- [`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](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount.md#mechanics)
- - 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount.md#mechanics)
- Starting in MongoDB 8.0.10, you can reshard a time series collection. All shards in the time series collection must run version 8.0.10 or later to reshard. — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-limitations.md#resharding)
- You would set these values in the [configuration file](https://www.mongodb.com/docs/manual/reference/configuration-options.md#std-label-configuration-options) or on the command line for your [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance. — [source](https://www.mongodb.com/docs/manual/reference/log-messages.md#systemlog-verbosity-settings)
- - On the [shard](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-shard) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) that merges the results. — [source](https://www.mongodb.com/docs/manual/reference/log-messages.md#time-waiting-for-shards-logged-in-remoteopwaitmillis-field)
- The projection shows the scaled amounts are now random values in the range from 0 to 99. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rand.md#generate-random-data-points)
- | 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](https://www.mongodb.com/docs/manual/reference/command/currentOp.md#behavior)
- Calculated across all shards, the lowest estimate of the number of seconds remaining. — [source](https://www.mongodb.com/docs/manual/reference/command/currentOp.md#output-fields)
- Calculated across all shards, the highest estimate of the number of seconds remaining. — [source](https://www.mongodb.com/docs/manual/reference/command/currentOp.md#output-fields)
- Starting in MongoDB 5.0, [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod), [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), and the legacy [`mongo`](https://www.mongodb.com/docs/manual/reference/mongo.md#mongodb-binary-bin.mongo) shell no longer support `x86_64` platforms which do not meet this minimum microarchitecture requirement. — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#x86-64)
- Starting in MongoDB 5.0, [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod), [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), and the legacy [`mongo`](https://www.mongodb.com/docs/manual/reference/mongo.md#mongodb-binary-bin.mongo) shell no longer support `arm64` platforms which do not meet this minimum microarchitecture requirement. — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#arm64)
- The [`connPoolStats`](https://www.mongodb.com/docs/manual/reference/command/connpoolstats.md#mongodb-dbcommand-dbcmd.connPoolStats) command returns information regarding the number of open connections to the current database for [`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 in sharded clusters. — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#manage-connection-pool-sizes)
- You need to restart [`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) processes for new system-wide keepalive settings to take effect. — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#adjust-tcp-keepalive-time)
- Keepalive values greater than `300` seconds, (5 minutes) will be overridden on [`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) sockets and set to `300` seconds. — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#adjust-tcp-keepalive-time)
- Windows users should consider the [Windows Server Technet Article on KeepAliveTime](https://technet.microsoft.com/en-us/library/cc957549.aspx) for more information on setting keepalive for MongoDB deployments on Windows systems. Keepalive values greater than or equal to *600000* milliseconds (10 minutes) will be ignored by [`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) — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#adjust-tcp-keepalive-time)
- At a minimum, ensure that each [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance has access to two real cores or one multi-core physical CPU. — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#allocate-sufficient-ram-and-cpu)
- On Linux, you must disable *zone reclaim* and also ensure that your [`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) instances are started by `numactl`, which is generally configured through your platform's init system. You must perform both of these operations to properly disable NUMA for use with MongoDB. — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#configuring-numa-on-linux)
- 2. Ensure that [`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) are started by `numactl`. This is generally configured through your platform's init system. Run the following command to determine which init system is in use on your platform: — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#configuring-numa-on-linux)
- You must use `numactl` to start each of your [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instances, including all [config servers](https://www.mongodb.com/docs/manual/core/sharded-cluster-config-servers.md#std-label-sharding-config-server), [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances, and clients. Edit the default **systemd** service file for each as follows: — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#configuring-numa-on-linux)
- 5. If applicable, repeat these steps for any [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances. — [source](https://www.mongodb.com/docs/manual/administration/production-notes.md#configuring-numa-on-linux)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.count.md#definition)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/changeStreamSplitLargeEvent.md#mongodb-shell)
- The `{ _id: 0 }` [projection](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#std-label-method-find-projection) suppresses the `_id` field in the output. — [source](https://www.mongodb.com/docs/manual/core/views/create-view.md#query-the-view)
- **Note: Projection Restrictions** — [source](https://www.mongodb.com/docs/manual/core/views/create-view.md#query-the-view)
- ```javascript db.createView( "medicalView", "medical", [ { $set: { "diagnosisCode": { $cond: { if: { $in: [ "Provider", "$$USER_ROLES.role" ] }, then: "$diagnosisCode", else: "$$REMOVE" } } }, }, { $set: { "creditCard": { $cond: { if: { $in: [ "Billing", "$$USER_ROLES.role" ] }, then: "$creditCard", else: "$$REMOVE" } } } } ] ) ``` — [source](https://www.mongodb.com/docs/manual/core/views/create-view.md#retrieve-medical-information-for-roles-granted-to-the-current-user)
- ```javascript [ { _id: 0, patientName: 'Jack Jones', creditCard: '1234-5678-9012-3456' }, { _id: 1, patientName: 'Mary Smith', creditCard: '6541-7534-9637-3456' } ] ``` — [source](https://www.mongodb.com/docs/manual/core/views/create-view.md#retrieve-medical-information-for-roles-granted-to-the-current-user)
- ```javascript [ { _id: 0, patientName: 'Jack Jones', diagnosisCode: 'CAS 17' }, { _id: 1, patientName: 'Mary Smith', diagnosisCode: 'ACH 01' } ] ``` — [source](https://www.mongodb.com/docs/manual/core/views/create-view.md#retrieve-medical-information-for-roles-granted-to-the-current-user)
- ```javascript { _id: 0, myRoles: [ { _id: 'test.Operations', role: 'Operations', db: 'test' }, { _id: 'test.Sales', role: 'Sales', db: 'test' }, { _id: 'test.read', role: 'read', db: 'test' } ] } ``` — [source](https://www.mongodb.com/docs/manual/core/views/create-view.md#roles-with-the-same-name-in-multiple-databases)
- 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](https://www.mongodb.com/docs/manual/reference/method/cursor.map.md)
- | Parameter | Type | Description | | --- | --- | --- | | `function` | function | A function to apply to each document visited by the cursor. | — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.map.md)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.map.md#behavior)
- For information on how to list sharding operations that are active on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos), see the `localOps` parameter in [`$currentOp`.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-pipeline-pipe.-currentOp) — [source](https://www.mongodb.com/docs/manual/reference/command/killOp.md#sharded-cluster)
- `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](https://www.mongodb.com/docs/manual/reference/method/cursor.tryNext.md#behavior)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS.md#definition)
- Routing with mongos: The mongos acts as a query router, providing an interface between client applications and the sharded cluster. — [source](https://www.mongodb.com/docs/manual/sharding/)
- If queries do not include the shard key or the prefix of a compound shard key, mongos performs a broadcast operation, querying all shards in the sharded cluster. These scatter/gather queries can be long running operations. — [source](https://www.mongodb.com/docs/manual/sharding/)
- You must connect to a mongos router to interact with any collection in the sharded cluster. This includes sharded and unsharded collections. Clients should never connect to a single shard to perform read or write operations. — [source](https://www.mongodb.com/docs/manual/sharding/)
- Starting in MongoDB 8.3, you can only run DDL operations and applyOps on a mongos for all sharded clusters. For Atlas clusters, these operations may be temporarily unavailable while transitioning from a replica set to a sharded cluster. — [source](https://www.mongodb.com/docs/manual/sharding/)
- You can connect to a mongos the same way you connect to a mongod using the mongosh or a MongoDB driver. — [source](https://www.mongodb.com/docs/manual/sharding/)
- Starting in MongoDB 9.0, the COUNT_SCAN, GEO_NEAR_2D, GEO_NEAR_2DSPHERE, and UPDATE stages also report this field. — [source](https://www.mongodb.com/docs/manual/reference/explain-results/)
- COUNT_SCAN, GEO_NEAR_2D, GEO_NEAR_2DSPHERE, GROUP, SORT, UPDATE — [source](https://www.mongodb.com/docs/manual/reference/explain-results/)
- serverInfo: { // serverInfo for mongos — [source](https://www.mongodb.com/docs/manual/reference/explain-results/)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#definition)
- - For a sharded cluster, you must issue [`db.collection.watch()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#mongodb-method-db.collection.watch) on a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#deployment)
- - 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#behavior)
- - 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#full-document-lookup-of-update-operations)
- MongoDB provides multiple ways to iterate on a cursor. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#cursor-iteration)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#cursor-iteration)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#cursor-iteration)
- The following operation opens a change stream cursor against the `data.sensors` collection: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#open-a-change-stream)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#open-a-change-stream)
- The following operation opens a change stream cursor against the `data.sensors` collection using the `fullDocument : "updateLookup"` option. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#change-stream-with-full-document-update-lookup)
- The following example creates a change stream cursor for the `temperatureSensor` collection using `fullDocumentBeforeChange: "whenAvailable"`: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#change-stream-with-document-pre-image)
- - The `while` loop runs until the cursor is closed. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#change-stream-with-document-pre-image)
- The following example creates a change stream cursor for the `temperatureSensor` collection using `fullDocument: "whenAvailable"`: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#change-stream-with-document-post-image)
- The following operation opens a change stream cursor against the `data.sensors` collection using an aggregation pipeline to filter only `insert` events: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#change-stream-with-aggregation-pipeline-filter)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#change-stream-with-aggregation-pipeline-filter)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#change-stream-with-aggregation-pipeline-filter)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#resuming-a-change-stream)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.watch.md#resuming-a-change-stream)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- 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](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#cursor)
- | 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](https://www.mongodb.com/docs/compass/schema/export.md#expanded-format-schema-object-properties)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#join-conditions-and-subqueries-on-a-foreign-collection)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md)
- - 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](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#change-streams)
- - 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](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#change-streams)
- 2. Create a cursor variable — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#examples)
- ```javascript sensorCursor.count() ``` — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#examples)
- 4. Return the first document from the cursor — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#examples)
- ```javascript { _id: 0, temperature: 12 } ``` — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#examples)
- 6. Return the next document from the cursor — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#examples)
- 7. Attempt to return the next document from the cursor — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.isExhausted.md#examples)
- MongoDB includes the `_id` field by default. To exclude the `_id` field from the `$project` stage, set the `_id` field to `0` in the projection document. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#suppress-id-field-in-the-output-documents)
- The `cursor.addOption()` method has the following parameter: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.addOption.md#definition)
- | 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](https://www.mongodb.com/docs/manual/reference/method/cursor.addOption.md#definition)
- [`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](https://www.mongodb.com/docs/manual/reference/method/cursor.addOption.md#flags)
- | Example | Results | | --- | --- | | `{ $reverseArray: { $literal: [ 1, 2, 3 ] } }` | `[ 3, 2, 1 ]` | | `{ $reverseArray: { $slice: [ [ "foo", "bar", "baz", "qux" ], 1, 2 ] } } }` | `[ "baz", "bar" ]` | | `{ $reverseArray: null }` | `null` | | `{ $reverseArray: { $literal: [ ] } }` | `[ ]` | | `{ $reverseArray: { $literal: [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] } }` | `[ [ 4, 5, 6 ], [ 1, 2, 3 ] ]` | — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/reverseArray.md#behavior)
- 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsSecond.md#use-tssecond-in-a-change-stream-cursor-to-monitor-collection-changes)
- A [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance routes a query to a [cluster](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-sharded-cluster) by: — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#routing-and-results-process)
- [Aggregation operations](https://www.mongodb.com/docs/manual/core/aggregation-pipeline.md#std-label-aggregation-pipeline) running on multiple shards may route results back to the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) to merge results if they don't need to run on the database's [primary shard.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-primary-shard) — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#routing-and-results-process)
- There are two cases in which a pipeline is ineligible to run on [`mongos`.](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) — [source](https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router.md#routing-and-results-process)
- - 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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sum.md#example)
- ```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](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/unpack-arrays.md#steps)
- For the database command, see the [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) command. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#definition)
- The `db.collection.count()` method has the following form: — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#syntax)
- | Parameter | Type | Description | | --- | --- | --- | | `query` | document | The query selection criteria. | | `options` | document | Optional. Extra options for modifying the count. | — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#parameters)
- `count()` is equivalent to the `db.collection.find(query).count()` construct. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#fields)
- Connect [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) to the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) for your sharded cluster. Specify the `host` and `port` on which the `mongos` is running: — [source](https://www.mongodb.com/docs/manual/core/timeseries/timeseries-shard-collection.md#create-a-sharded-time-series-collection)
- Instructs the server to avoid closing a cursor automatically after a period of inactivity. — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.noCursorTimeout.md#definition)
- The [`noCursorTimeout()`](https://www.mongodb.com/docs/manual/reference/method/cursor.nocursortimeout.md#mongodb-method-cursor.noCursorTimeout) method has the following prototype form: — [source](https://www.mongodb.com/docs/manual/reference/method/cursor.noCursorTimeout.md#definition)
- The `$in` operator selects the documents where the value of a field equals any value in the specified array. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md)
- You can use `$in` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#compatibility)
- The `$in` operator has the following form: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#syntax)
- You can specify projection in two ways for [`find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#mongodb-method-db.collection.find) and [`findOne()`:](https://www.mongodb.com/docs/manual/reference/method/db.collection.findone.md#mongodb-method-db.collection.findOne) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne.md#projection)
- - Setting the `options` parameter to `projection` — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne.md#projection)
- If you specify both parameters, the `projection` parameter takes precedence. To use `options.projection`, set the `projection` parameter to `null` or `undefined`. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne.md#projection)
- 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](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
- 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](https://oneuptime.com/blog/post/2026-03-31-mongodb-index-for-count-operations/markdown)
- - The [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage uses a regular expression to filter out the city documents, leaving only those containing a state. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/split.md#example)
- | Input Type | Behavior | | --- | --- | | Array | Returns true | | Binary data | Returns true | | Boolean | No-op. Returns the boolean value. | | Code | Returns true | | Date | Returns true | | Decimal | Returns true if not zeroReturn false if zero | | Double | Returns true if not zeroReturn false if zero | | Integer | Returns true if not zeroReturn false if zero | | JavaScript | Returns true | | Long | Returns true if not zeroReturn false if zero | | MaxKey | Returns true | | MinKey | Returns true | | Null | Returns null | | Object | Returns true | | ObjectId | Returns true | | Regular expres — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toBool.md#behavior)
- A query with an implicit match against a regular expression is equivalent to a query that uses the `$regex` operator. The following queries return the same result: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#regex-match-behavior)
- However, `$regexMatch` ignores collation. The following regular expression pattern matching examples are case-sensitive and diacritic sensitive: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexMatch.md#regexmatch-and-collation)
- You can use case sensitivity with negated terms (terms prefixed with `-`). — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#case-sensitive-negated-term-search)
- You can use diacritic sensitivity with negated terms (terms prefixed with `-`). — [source](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#diacritic-sensitive-negated-term-search)
- | BSON Type | Canonical Extended JSON | Relaxed Extended JSON | | --- | --- | --- | | Int32 | `{"$numberInt": "42"}` | `42` | | Int64 | `{"$numberLong": "42"}` | `42` | | Double | `{"$numberDouble": "42.5"}` | `42.5` | | ObjectId | `{"$oid": "<object-id>"}` | Same as Canonical | | Date | `{"$date": {"$numberLong": "1609459200000"}}` | `{"$date": "2021-01-01T00:00:00.000Z"}` | | Binary | `{"$binary": {"base64": "AQIDBA==", "subType": "00"}}` | Same as Canonical | | Regular Expression | `{"$regularExpression": {"pattern": "abc", "options": "i"}}` | Same as Canonical | — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/serializeEJSON.md#comparison-of-canonical-and-relaxed-formats)
- As an alternative, use $expr instead. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
- You can use `$not` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#compatibility)
- The [`$not`](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#mongodb-query-op.-not) operator has the following form: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#syntax)
- - Regular expression objects, such as `/pattern/`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#regular-expressions)
- The following two queries return movies where `runtime` is greater than `1000` minutes and `title` does not start with the letter `T`. The first query passes a string to `$regex`: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#regular-expressions)
- The second query passes a regex literal to `$regex`: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#regular-expressions)
- - Driver language regular expression objects. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#regular-expressions)
- | Input Type | Behavior | | --- | --- | | Array | Returns the [`Array`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Array) as a string. **New in version 8.3** | | BinData | If the [`BinData`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Binary) is a UUID, returns the UUID as a string. Otherwise, returns the base64 encoded string value. | | Boolean | Returns the Boolean value as a string. | | Date | Returns the [`Date`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Da — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#behavior)
- Compare that with the following query which uses the [`$nor`](https://www.mongodb.com/docs/manual/reference/operator/query/nor.md#mongodb-query-op.-nor) operator with the [`$exists`](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#mongodb-query-op.-exists) operator: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nor.md#nor-and-exists)
- You can use `$expr` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#compatibility)
- The following operation uses [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) to find documents in the `movies` collection where the Rotten Tomatoes viewer rating exceeds the critic rating: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#compare-two-fields-from-a-single-document)
- The following example uses `$expr` with [`$cond`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/cond.md#mongodb-expression-exp.-cond) to calculate the weighted score based on `imdb.votes` and [`$gt`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/gt.md#mongodb-expression-exp.-gt) to return documents whose calculated weighted score is greater than `9`: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#use-expr-with-conditional-statements)
- { type: { $ne: "movie" } }, — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- Inequality operators such as $ne or $nin are range operators, not equality operators. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/)
- ```javascript db.budget.aggregate( [ { $match: { $expr: { $not: { $eq: [ { $setIntersection: [ "$allowedRoles", "$$USER_ROLES.role" ] }, [] ] } } } } ] ) ``` — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setIntersection.md#retrieve-documents-for-roles-granted-to-the-current-user)
- ```javascript embedded_pl = [ // Stage 1: Match the values of two fields on each side of the join // The $eq filter uses aliases for the name and variation fields set { $match: { $expr: { $and: [ { $eq: ["$product_name", "$$prdname"] }, { $eq: ["$product_variation", "$$prdvartn"] } ] } } }, — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- // Match products ordered in 2020 { $match: { orders: { $ne: [] } } }, — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```python embedded_pl = [ { "$match": { "$expr": { "$and": [ {"$eq": ["$product_name", "$$prdname"]}, {"$eq": ["$product_variation", "$$prdvartn"]}, ] } } } ] — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```python pipeline.append({"$match": {"orders": {"$ne": []}}}) — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- bson_array_builder_append_document(bab, BCON_NEW( "$match", "{", "$expr", "{", "$and", "[", "{", "$eq", "[", BCON_UTF8("$product_name"), BCON_UTF8("$$prdname"), "]", "}", "{", "$eq", "[", BCON_UTF8("$product_variation"), BCON_UTF8("$$prdvartn"), "]", "}", "]", "}", "}")); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```c "{", "$match", "{", "orders", "{", "$ne", "[", "]", "}", "}", "}", ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```cpp auto embed_match_stage1 = bsoncxx::from_json(R"({ "$match": { "$expr": { "$and": [ { "$eq": ["$product_name", "$$prdname"] }, { "$eq": ["$product_variation", "$$prdvartn"] } ] } } })"); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```cpp pipeline.match(bsoncxx::from_json(R"({ "orders": { "$ne": [] } })")); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- embedded_pl.push({ $match: { $expr: { $and: [ { $eq: ['$product_name', '$$prdname'] }, { $eq: ['$product_variation', '$$prdvartn'] }, ], }, }, }); — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```javascript pipeline.push({ $match: { orders: { $ne: [] }, }, }); — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```ruby { "$match": { "$expr": { "$and": [ { "$eq": ["$product_name", "$$prdname"] }, { "$eq": ["$product_variation", "$$prdvartn"] }, ], }, }, }, ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```ruby { "$match": { orders: { "$ne": [] }, }, }, ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```rust let mut embedded_pipeline = Vec::new(); embedded_pipeline.push(doc! { "$match": { "$expr": { "$and": [ { "$eq": ["$product_name", "$$prdname"] }, { "$eq": ["$product_variation", "$$prdvartn"] } ] } } }); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- ```rust pipeline.push(doc! { "$match": { "orders": { "$ne": [] } } }); ``` — [source](https://www.mongodb.com/docs/manual/tutorial/aggregation-examples/multi-field-join.md#steps)
- In addition to the `false` boolean value, [`$not`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#mongodb-expression-exp.-not) evaluates as `false` the following: `null`, `0`, and `undefined` values. The [`$not`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#mongodb-expression-exp.-not) evaluates all other values as `true`, including non-zero numeric values and arrays. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#behavior)
- | Example | Result | | --- | --- | | `{ $not: [ true ] }` | `false` | | `{ $not: [ [ false ] ] }` | `false` | | `{ $not: [ false ] }` | `true` | | `{ $not: [ null ] }` | `true` | | `{ $not: [ 0 ] }` | `true` | — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#behavior)
- The following operation uses the [`$not`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#mongodb-expression-exp.-not) operator to determine if `qty` is not greater than `250`: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/not.md#example)
- You can use `$exists` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#compatibility)
- [Expressions](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) do not support the [`$exists`](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#mongodb-query-op.-exists) operator. To check for the existence of a field in an expression, you can use the [`$type`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/type.md#mongodb-expression-exp.-type) aggregation operator to check if a field has a type of `missing`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#compatibility)
- ```javascript const findResult = await encryptedCollection.findOne( { $expr: { $encStrStartsWith: { input: "$patientRecord.ssn", prefix: "987" } } }) ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```javascript const findResult = await encryptedCollection.findOne( { $expr: { $encStrContains: { input: "$patientRecord.ssn", substring: "-65-4" } } }) ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```python find_result = encrypted_collection.find_one( { "$expr": { "$encStrStartsWith": { "input": "$patientRecord.ssn", "prefix": "987" } } }) ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```python find_result = encrypted_collection.find_one( { "$expr": { "$encStrContains": { "input": "$patientRecord.ssn", "substring": "-65-4" } } }) ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```java Document filter = new Document("$expr", new Document("$encStrStartsWith", new Document() .append("input", "$patientRecord.ssn") .append("prefix", "987"))); — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```java Document filter = new Document("$expr", new Document("$encStrContains", new Document() .append("input", "$patientRecord.ssn") .append("substring", "-65-4"))); — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```rust let query = doc! { "$expr": doc! { "$encStrStartsWith": doc! { "input": "$patientRecord.ssn", "prefix": "987" } } }; let find_result = encrypted_coll.find_one(query).await?; — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```rust let query = doc! { "$expr": doc! { "$encStrContains": doc! { "input": "$patientRecord.ssn", "substring": "-65-4" } } }; let find_result = encrypted_coll.find_one(query).await?; — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```php $findResult = $encryptedCollection->findOne([ '$expr' => [ '$encStrStartsWith' => [ 'input' => '$patientRecord.ssn', 'prefix' => '987', ], ], ]); print_r($findResult); ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```php $findResult = $encryptedCollection->findOne([ '$expr' => [ '$encStrContains' => [ 'input' => '$patientRecord.ssn', 'substring' => '-65-4', ], ], ]); print_r($findResult); ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```ruby find_result = encrypted_collection.find( "$expr" => { "$encStrStartsWith" => { "input" => "$patientRecord.ssn", "prefix" => "987" } } ).first puts find_result.inspect ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- ```ruby find_result = encrypted_collection.find( "$expr" => { "$encStrContains" => { "input" => "$patientRecord.ssn", "substring" => "-65-4" } } ).first puts find_result.inspect ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-retrieve-encrypted-document.md#procedure)
- You can use `$where` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#compatibility)
- The [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) operator has the following form: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#syntax)
- - However, if you must create custom expressions, [`$function`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/function.md#mongodb-expression-exp.-function) is preferred over [`$where`.](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#syntax)
- The following JavaScript functions and properties **are available** to [`map-reduce operations`](https://www.mongodb.com/docs/manual/reference/command/mapreduce.md#mongodb-dbcommand-dbcmd.mapReduce) and [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) operator expressions: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#available-javascript-properties-and-functions)
- Only apply the [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) query operator to top-level documents. The [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) query operator will not work inside a nested document, for instance, in an [`$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/query/elemmatch.md#mongodb-query-op.-elemMatch) query. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#elemmatch)
- Using normal non-[`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) query statements provides the following performance advantages: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#considerations)
- The following example uses [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) and the `hex_md5()` JavaScript function to compare the value of the `name` field to an MD5 hash and returns any matching document. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#example)
- If you must create custom expressions, [`$function`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/function.md#mongodb-expression-exp.-function) is preferred over [`$where`.](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) — [source](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#example)
- [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) does not permit references to the `db` object from the [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) function. This is uncommon in un-sharded collections. — [source](https://www.mongodb.com/docs/manual/reference/limits.md#sharding-operational-restrictions)
- If a field is missing from a document, [`$ne`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/ne.md#mongodb-expression-exp.-ne) treats the missing field as a distinct value, separate from `null`. [`$ne`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/ne.md#mongodb-expression-exp.-ne) considers two missing fields equivalent to each other, and considers a missing field different from a `null` value. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/ne.md#definition)
- The [`$ne`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/ne.md#mongodb-expression-exp.-ne) compares both value and type, using the [specified BSON comparison order](https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order.md#std-label-bson-types-comparison-order) for values of different types. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/ne.md#definition)
- | Field | Description | Example | | --- | --- | --- | | `match` | An ECMAScript-formatted regular expression (regex) to match against a provided username. Each parenthesis-enclosed section represents a regex capture group used by `substitution` or `ldapQuery`. | `"(.+)ENGINEERING"` `"(.+)DBA"` | | `substitution` | An LDAP distinguished name (DN) formatting template that converts the authentication name matched by the `match` regex into a LDAP DN. Each curly bracket-enclosed numeric value is replaced by the corresponding [regex capture group](http://www.regular-expressions.info/refcapture.html) — [source](https://www.mongodb.com/docs/manual/reference/program/mongod.md#ldap-authentication-or-authorization-options)
- - The following operation uses the [`$regex`](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#mongodb-query-op.-regex) operator to return documents in the [bios collection](https://www.mongodb.com/docs/manual/reference/bios-example-collection.md) where `name.last` field starts with the letter `N` (or is `"LIKE N%"`) — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#query-using-operators)
- ```javascript db.bios.find( { "name.last": { $regex: /^N/ } } ) ``` — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#query-using-operators)
- For example, to define variables that you can access elsewhere in the `find` method, use the `let` option. To filter results using a variable, you must access the variable within the [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) operator. — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#use-variables-in-let-option)
- ```javascript db.budget.find( { $expr: { $not: { $eq: [ { $setIntersection: [ "$allowedRoles", "$$USER_ROLES.role" ] }, [] ] } } } ) ``` — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.find.md#retrieve-documents-for-roles-granted-to-the-current-user)
- You can use `$ne` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#compatibility)
- The `$ne` operator has the following form: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#syntax)
- The following example sets the `highestRated` field based on a `$ne` comparison on a field in an embedded document. The [`updateMany()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.updatemany.md#mongodb-method-db.collection.updateMany) operation searches for an embedded document, `imdb`, with a subfield named `rating`. It uses [`$set`](https://www.mongodb.com/docs/manual/reference/operator/update/set.md#mongodb-update-up.-set) to update the `highestRated` field to `false` in each document where the value of `rating` is not equal to `9.3` or where the `rating` subfield do — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#update-based-on-not-equal-embedded-document-fields)
- - **Scalar comparison**: `$ne` matches documents where the scalar value is not present as an element in the array, including documents that don't have the field. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#arrays)
- - **Exact array comparison**: `$ne` matches documents where the field array is not identical to the specified array, including documents with a different element order, a different number of elements, or a missing field. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#arrays)
- ```javascript const uri = "<Your Connection String>"; const keyVaultClient = new MongoClient(uri); await keyVaultClient.connect(); const keyVaultDB = keyVaultClient.db(keyVaultDatabase); // Drop the Key Vault Collection in case you created this collection // in a previous run of this application. await keyVaultDB.dropDatabase(); const keyVaultColl = keyVaultDB.collection(keyVaultCollection); await keyVaultColl.createIndex( { keyAltNames: 1 }, { unique: true, partialFilterExpression: { keyAltNames: { $exists: true } }, } ); ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/tutorials/explicit-encryption.md#procedure)
- key_vault_client[key_vault_db][key_vault_coll].create_index( [("keyAltNames", ASCENDING)], unique=True, partialFilterExpression={"keyAltNames": {"$exists": True}}, ) ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/tutorials/explicit-encryption.md#procedure)
- MongoCollection keyVaultCollection = keyVaultClient.getDatabase(keyVaultDb).getCollection(keyVaultColl); IndexOptions indexOpts = new IndexOptions().partialFilterExpression(new BsonDocument("keyAltNames", new BsonDocument("$exists", new BsonBoolean(true) ))).unique(true); keyVaultCollection.createIndex(new BsonDocument("keyAltNames", new BsonInt32(1)), indexOpts); keyVaultClient.close(); ``` — [source](https://www.mongodb.com/docs/manual/core/queryable-encryption/tutorials/explicit-encryption.md#procedure)
- You can use `$nin` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#compatibility)
- The [`$nin`](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#mongodb-query-op.-nin) operator has the following form: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#syntax)
- If `field` has an array, the [`$nin`](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#mongodb-query-op.-nin) operator selects the documents whose `field` has an array with **no** element equal to a value in the specified array. For example, `<value1>`, `<value2>`, and so on. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#syntax)
- ```javascript // Attempt to find and modify document db.medical.findAndModify( { query: { $and: [ { // Only update the document for Mary Smith patientName: { $eq: "Mary Smith" } }, { // User must have the Provider role to perform the update $expr: { $ne: [ { $setIntersection: [ [ "Provider" ], "$$USER_ROLES.role" ] }, [] ] } } ] }, // Update document update: { patientName: "Mary Smith", diagnosisCode: "ACH 03", creditCard: "6541-7534-9637-3456" } } ) ``` — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findAndModify.md#user-roles-and-document-updates)
- The `{ metacritic : { $ne : null } }` query matches documents where the `metacritic` field exists **and** has a non-null value. — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#non-equality-filter)
- The `{ a: { $ne: null } }` query returns the complement, which is every document that `{ a: null }` does not match. The query matches the documents with `_id` values `2`, `3`, `5`, and `6`, including the document that holds an empty array. — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#equality-on-an-array-field)
- The `{ "a.b": { $ne: null } }` query returns the complement, which is every document that `{ "a.b": null }` does not match: the documents with `_id` values `2`, `3`, `4`, and `5`. That result is not the same as the set of documents that have a non-null value for `a.b`. Neither `_id: 2` nor `_id: 3` has any value at `a.b`, yet the `{ $ne: null }` filter still matches them. A `{ $ne: null }` filter on a dotted path does not necessarily return the same documents as an [`$exists`](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#mongodb-query-op.-exists) check on that path. — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#equality-on-a-dotted-path)
- Reference documentation for the [`$type`](https://www.mongodb.com/docs/manual/reference/operator/query/type.md#mongodb-query-op.-type) and [`$exists`](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#mongodb-query-op.-exists) operators. — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#existence-check)
- The `{ item : { $ne : null } }` query matches documents where the `item` field exists **and** has a non-null value. — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#non-equality-filter)
- ```javascript { description : { $exists: false } } ``` — [source](https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields.md#query-for-null-or-missing-fields-with-mongodb-atlas)
- { runtime: { $not: { $eq: 120 } } } — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- { runtime: { $ne: 120 } } — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- { runtime: { $not: 120 } } — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- { title: { $not: /^T/ }, runtime: { $gt: 1000 } }, — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- $regex operator expressions. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- { title: { $not: { $regex: "^T" } }, runtime: { $gt: 1000 } }, — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- { title: { $not: { $regex: /^T/ } }, runtime: { $gt: 1000 } }, — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- The matches field can use regular expressions. — [source](https://www.mongodb.com/docs/atlas/configure-alerts.md#configure-an-alert)
- Provides regular expression capabilities for pattern matching *strings* in queries. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#definition)
- You can use `$regex` for deployments hosted in the following environments: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#compatibility)
- You can also use regular expression objects (`/pattern/`) to specify regular expressions: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#syntax)
- The following `<options>` are available for regular expressions: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#syntax)
- `$regex` doesn't support the global search modifier `g`. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#syntax)
- The following example uses the `$regex` operator to find `name` field strings that match the regular expression `"(?i)a(?-i)cme"`: — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#pcre-versus-javascript)
- ```javascript db.inventory.find( { item: { $not: { $regex: "^p.*" } } } ) db.inventory.find( { item: { $not: { $regex: /^p.*/ } } } ) ``` — [source](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#regex-and-not)
- - Inequality operators such as [`$ne`](https://www.mongodb.com/docs/manual/reference/operator/query/ne.md#mongodb-query-op.-ne) or [`$nin`](https://www.mongodb.com/docs/manual/reference/operator/query/nin.md#mongodb-query-op.-nin) are range operators, not equality operators. — [source](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline.md#additional-considerations)
- The second [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage uses `$rand` in a match expression to further refine the selection. For each document, `$rand` generates a value between 0 and 1. The threshold of `0.5` in the less than [`($lt)`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lt.md#mongodb-expression-exp.-lt) comparison means that [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) will be true for about half the documents. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rand.md#select-random-items-from-a-collection)
- ```javascript db.createView( "budgetView", "budget", [ { $match: { $expr: { $not: { $eq: [ { $setIntersection: [ "$allowedRoles", "$$USER_ROLES.role" ] }, [] ] } } } } ] ) ``` — [source](https://www.mongodb.com/docs/manual/core/views/create-view.md#retrieve-budget-documents-for-roles-granted-to-the-current-user)
- Expressions do not support the $exists operator. To check for the existence of a field in an expression, you can use the $type aggregation operator to check if a field has a type of missing. — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists/)
- MongoDB supports regular expression [`$regex`](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#mongodb-query-op.-regex) queries to perform string pattern matches. — [source](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#specify-and-as-well-as-or-conditions)
- Regular expression syntax differs between `mongosh` and drivers. `mongosh` uses JavaScript regex literals (for example, `{ title: /^T/ }`). The drivers use the equivalent `$regex` operator (for example, `{ title: { $regex: '^T' } }`). — [source](https://www.mongodb.com/docs/manual/tutorial/query-documents.md#specify-and-as-well-as-or-conditions)
- The following new concise syntax removes the requirement for an equality match on the foreign and local fields inside an [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) operator: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#correlated-subqueries-using-concise-syntax)
- Pipelines can execute on a foreign collection and include multiple join conditions. The [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) operator enables more complex join conditions including conjunctions and non-equality matches. — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#use-multiple-join-conditions-and-a-correlated-subquery)
- The following query filter uses the [`$not`](https://www.mongodb.com/docs/manual/reference/operator/query/not.md#mongodb-query-op.-not) operator to find all documents where the value of the `name` field is **not** equal to "Andrea Le", or the `name` field does not exist: — [source](https://www.mongodb.com/docs/atlas/atlas-ui/query/filter.md#match-by-exclusion-not)
- The following query filter uses the [`$regex`](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#mongodb-query-op.-regex) operator to find all documents where the value of `email` includes the term "andrea\_le": — [source](https://www.mongodb.com/docs/atlas/atlas-ui/query/filter.md#match-by-substring)
- The query operator [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) can also be used to specify JavaScript expression. However: — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/function.md#alternative-to-where)
- **Note: Aggregation Alternatives Preferred over $where** — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/function.md#example-2-alternative-to-where)

## Related concepts

- cursor — is a part of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- projection — is a part of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- index — is a related of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- count — is a part of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- query operator anti-pattern — is a problem of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- sharded query targeting — is a part of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- pagination — is a part of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- query shape — is a related of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- $in — is a part of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- read preference — is a related of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
- query optimization — is a hypernym of MongoDB query shape optimization: sort, pagination, operators and sharded targeting
