<!-- llms-explorer concept facts · https://llms-explorer.com/tree/mongodb-query-operators-bounds-and-projection/ · pack 2026-10-19 · ~64835 tokens -->

# MongoDB query operators, index bounds and projection

> Everything the scanned sources say about MongoDB query operators, index bounds and projection: 890 source-anchored units across 5 sources, grouped by facet.

Parent: [Global AI Hub Research Corpus](https://llms-explorer.com/tree/global-ai-hub-research-corpus/) · 9 facets · 878 facts · page: https://llms-explorer.com/tree/mongodb-query-operators-bounds-and-projection/

## Definitions

- - 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)
- 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)
- 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 `<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/)
- 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 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 `$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)
- 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)
- 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)
- [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)
- 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)
- 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)
- 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 `{ $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)
- 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)
- 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)
- 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)
- 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)
- 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)
- 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/)
- 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

- 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/)
- 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)
- 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)
- 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/)
- 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/)
- 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/)
- `$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)
- | 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)
- 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)
- $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)
- 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)
- 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 $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/)
- 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/)
- 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/)
- 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)
- 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 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 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)
- 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 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)
- Use a Sparse Index to Improve $exists Performance — [source](https://www.mongodb.com/docs/manual/reference/operator/query/exists/)
- 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 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 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)
- 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 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 [`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 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)
- 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.movies.find(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#use-in-with-a-regular-expression)
- ```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.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 — `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.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 — `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)
- ```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)
- ```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.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/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.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 — `{ 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)
- ```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)
- ```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.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.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 — `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)
- ```javascript — `db.runCommand(` … — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheSetFilter.md#syntax)
- ```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)
- ```none — `"filters" : [` … — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheListFilters.md#output)
- ```javascript — `db.getSiblingDB("admin").aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.currentOp.md#active-indexing-operations)
- ```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.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.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.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)
- ```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 — `_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 — `db.jsonStrings.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toObject.md#convert-string-to-object)
- ```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 — `_id: 0,` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateTrunc.md#truncate-order-dates-in-a-project-pipeline-stage)
- ```javascript — `db.stockSales.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tsIncrement.md#obtain-the-incrementing-ordinal-from-a-timestamp-field)
- ```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)
- ```csharp — `var filter = Builders<Movie>.Filter.Text("future");` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#meta-indexkey)
- ```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.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.grades.findOneAndUpdate(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate.md#project-the-returned-document)
- ```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.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 — `{ _id: 0, result: 127 },` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bitXor.md#example)
- ```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)
- ```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)
- ```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.suppliers.aggregate([` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionWith.md#duplicate-results)
- ```javascript — `{ _id: 0 }` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto.md#comparing-different-granularities)
- ```javascript — `db.scores.findOneAndDelete(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndDelete.md#projecting-the-deleted-document)
- ```javascript — `db.scores.findOneAndReplace(` … — [source](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndReplace.md#project-specific-fields-in-return-document)
- ```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 — `db.theaters.find(` … — [source](https://www.mongodb.com/docs/manual/core/query-optimization.md#embedded-documents)
- ```javascript — `db.movies.aggregate( [` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#id-field-generation)
- ```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 — `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.survey.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/allElementsTrue.md#example)
- ```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.donors.aggregate(` … — [source](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rand.md#generate-random-data-points)
- ```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 — `{ 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/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 — `{ 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)
- 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)

## Problems, failure modes and limitations

- | 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)
- - [`$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)
- 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)
- | 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)
- 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)
- [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)
- 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/)
- 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)
- 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)
- 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/)
- 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/)
- | 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)
- [`$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)
- 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)
- 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)
- - 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)
- 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)
- [`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)
- - `$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)
- - 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)
- 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)
- 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)
- 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)
- $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/)
- | 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)
- - 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)
- - 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)
- 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)
- 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 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 | | --- | --- | --- | | `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)
- 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)
- | 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)
- 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)
- 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)
- $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/)
- 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)
- 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)
- 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)
- 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/)
- 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

- 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)
- 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)
- 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)
- 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)
- | 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)
- 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)
- - [`$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)
- 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/)
- 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)
- 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)
- 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)
- 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)
- 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 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)
- 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)
- 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)
- - 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)
- 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)
- 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)
- ```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)
- 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)
- 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)
- 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/)
- 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)
- | 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)
- 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)
- 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/)
- 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/)
- - 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)
- 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)
- 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/)
- 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)
- 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/)
- 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)
- 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)
- 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/)
- 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 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)
- 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)
- 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)
- 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 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)
- 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)
- 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)
- 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 [`$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 query meets all other covered query requirements. — [source](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey/)
- 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)
- | 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)
- 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)
- | 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)
- 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/)
- - 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)
- - 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)
- 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)
- { _id: 0, type: "pepperoni", size: "small", price: 19, — [source](https://www.mongodb.com/docs/manual/core/query-shapes/)
- - 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)
- { _id: 0, temperatures: [ { value: 1 }, { value: 4 } ] }, — [source](https://www.mongodb.com/docs/manual/reference/command/distinct/)
- 2. Enter the projection document into the Project field. — [source](https://www.mongodb.com/docs/compass/query/project.md)
- ```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 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)
- - 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)
- 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)
- 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)
- 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)
- - 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 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)
- - 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)
- Projection stages, counted separately by projection type. — [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/)
- 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)
- 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 query projection explicitly excludes _id and includes only the query field. — [source](https://www.mongodb.com/docs/manual/core/index-wildcard/)
- 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/)
- 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)
- { _id: 0, title: 1, runtime: 1 } — [source](https://www.mongodb.com/docs/manual/reference/operator/query/not/)
- 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)
- 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)
- { _id: 0, title: 1, year: 1 } — [source](https://www.mongodb.com/docs/manual/reference/operator/query/or/)
- The projection associated with this filter. Can be an empty document. — [source](https://www.mongodb.com/docs/manual/reference/command/planCacheListFilters.md#output)
- // 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)
- "$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/)
- 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)
- 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)
- 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)
- ```javascript { _id: 0, temperature: 12 } ``` — [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)
- | 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 `$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)
- - 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

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