

# Supported MongoDB APIs, operations, and data types in Amazon DocumentDB
<a name="mongo-apis"></a>

Amazon DocumentDB (with MongoDB compatibility) is a fast, scalable, highly-available, and fully managed document database service that supports MongoDB workloads. Amazon DocumentDB is compatible with the MongoDB 3.6, 4.0, 5.0, and 8.0 APIs. This section lists the supported functionality. For support using MongoDB APIs and drivers, please consult the MongoDB Community Forums. For support using the Amazon DocumentDB service, please contact the appropriate AWS support team. For functional differences between Amazon DocumentDB and MongoDB, please see [Functional differences: Amazon DocumentDB and MongoDB](functional-differences.md). 

MongoDB commands and operators that are internal-only or not applicable to a fully-managed service are not supported and are not included in the list of supported functionality.

We have added over 50\$1 additional capabilities since launch, and will continue to work backwards from our customers to deliver the capabilities that they need. For information on the most recent launches, see [Amazon DocumentDB Announcements](https://aws.amazon.com/documentdb/resources/).

If there is a feature that isn't supported that you'd like us to build, let us know by sending an email with your accountID, the requested features, and use case to the [Amazon DocumentDB service team](mailto:documentdb-feature-request@amazon.com).
+ [Database commands](#mongo-apis-database)
+ [Query and projection operators](#mongo-apis-query)
+ [Update operators](#mongo-apis-update)
+ [Geospatial](#mongo-apis-geospatial)
+ [Cursor methods](#mongo-apis-cursor)
+ [Aggregation pipeline operators](#mongo-apis-aggregation-pipeline)
+ [Data types](#mongo-apis-data-types)
+ [Indexes](#mongo-apis-indexes)

## Database commands
<a name="mongo-apis-database"></a>

**Topics**
+ [Administrative Commands](#mongo-apis-dababase-administrative)
+ [Aggregation](#mongo-apis-dababase-aggregation)
+ [Authentication](#mongo-apis-dababase-authentication)
+ [Diagnostic commands](#mongo-apis-dababase-diagnostics)
+ [Query and write operations](#mongo-apis-dababase-query-write)
+ [Role management commands](#mongo-apis-database-role-management)
+ [Sessions commands](#mongo-apis-dababase-sessions)
+ [User management](#mongo-apis-dababase-user-management)
+ [Sharding commands](#mongo-apis-dababase-sharding)

### Administrative Commands
<a name="mongo-apis-dababase-administrative"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  Capped Collections  |  No  |  No  |  No  |  No  |  No  | 
|  cloneCollectionAsCapped  |  No  |  No  |  No  |  No  |  No  | 
|  collMod  |  Partial  |  Partial  |  Partial  |  Partial  |  Partial  | 
|  collMod: expireAfterSeconds  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  convertToCapped  |  No  |  No  |  No  |  No  |  No  | 
|  copydb  |  No  |  No  |  No  |  No  |  No  | 
|  create  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  createView  |  No  |  No  |  No  |  Yes  |  No  | 
|  createIndexes  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  currentOp  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  drop  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  dropDatabase  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  dropIndexes  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  filemd5  |  No  |  No  |  No  |  No  |  No  | 
|  getAuditConfig  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  killCursors  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  killOp  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  listCollections\$1  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  listDatabases  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  listIndexes  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  reIndex  |  No  |  No  |  Yes  |  Yes  |  No  | 
|  renameCollection  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  setAuditConfig  |  No  |  Yes  |  Yes  |  Yes  |  No  | 

\$1 The `type` key in the filter option is not supported.

### Aggregation
<a name="mongo-apis-dababase-aggregation"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  aggregate  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  count  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  distinct  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  mapReduce  |  No  |  No  |  No  |  Yes  |  No  | 

### Authentication
<a name="mongo-apis-dababase-authentication"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  authenticate  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  logout  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Diagnostic commands
<a name="mongo-apis-dababase-diagnostics"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  buildInfo  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  collStats  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  connPoolStats  |  No  |  No  |  No  |  No  |  No  | 
|  connectionStatus  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  dataSize  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  dbHash  |  No  |  No  |  No  |  No  |  No  | 
|  dbStats  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  explain  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  explain: executionStats  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  features  |  No  |  No  |  No  |  No  |  No  | 
|  hostInfo  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  listCommands  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  profiler  |  [Yes](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [Yes](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [Yes](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [Yes](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  No  | 
|  serverStatus  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  top  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Query and write operations
<a name="mongo-apis-dababase-query-write"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  Change streams  |  [Yes](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [Yes](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [Yes](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [Yes](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  No  | 
|  delete  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  find  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  findAndModify  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  getLastError  |  No  |  No  |  No  |  No  |  No  | 
|  getMore  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  getPrevError  |  No  |  No  |  No  |  No  |  No  | 
|  GridFS  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  insert  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  parallelCollectionScan  |  No  |  No  |  No  |  No  |  No  | 
|  resetError  |  No  |  No  |  No  |  No  |  No  | 
|  update  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  ReplaceOne  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Role management commands
<a name="mongo-apis-database-role-management"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  createRole  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  dropAllRolesFromDatabase  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  dropRole  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  grantRolesToRole  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  revokeRolesFromRole  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  revokePrivilegesFromRole  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  rolesInfo  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  updateRole  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 

### Sessions commands
<a name="mongo-apis-dababase-sessions"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  abortTransaction  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  commitTransaction  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  endSessions  |  No  |  No  |  No  |  No  |  No  | 
|   killAllSessions  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  killAllSessionsByPattern  |  No  |  No  |  No  |  No  |  No  | 
|  killSessions  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  refreshSessions  |  No  |  No  |  No  |  No  |  No  | 
|  startSession  |  No  |  Yes  |  Yes  |  Yes  |  No  | 

### User management
<a name="mongo-apis-dababase-user-management"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  createUser  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  dropAllUsersFromDatabase  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  dropUser  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  grantRolesToUser  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  revokeRolesFromUser  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  updateUser  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  usersInfo  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Sharding commands
<a name="mongo-apis-dababase-sharding"></a>


| Command | Elastic cluster | 
| --- | --- | 
|  abortReshardCollection  |  No  | 
|  addShard  |  No  | 
|  addShardToZone  |  No  | 
|  balancerCollectionStatus  |  No  | 
|  balancerStart  |  No  | 
|  balancerStatus  |  No  | 
|  balancerStop  |  No  | 
|  checkShardingIndex  |  No  | 
|  clearJumboFlag  |  No  | 
|  cleanupOrphaned  |  No  | 
|  cleanupReshardCollection  |  No  | 
|  commitReshardCollection  |  No  | 
|  enableSharding  |  Yes  | 
|  flushRouterConfig  |  No  | 
|  getShardMap  |  No  | 
|  getShardVersion  |  No  | 
|  isdbgrid  |  No  | 
|  listShards  |  No  | 
|  medianKey  |  No  | 
|  moveChunk  |  No  | 
|  movePrimary  |  No  | 
|  mergeChunks  |  No  | 
|  refineCollectionShardKey  |  No  | 
|  removeShard  |  No  | 
|  removeShardFromZone  |  No  | 
|  reshardCollection  |  No  | 
|  setAllowMigrations  |  No  | 
|  setShardVersion  |  No  | 
|  shardCollection  |  Yes  | 
|  shardingState  |  No  | 
|  split  |  No  | 
|  splitVector  |  No  | 
|  unsetSharding  |  No  | 
|  updateZoneKeyRange  |  No  | 

## Query and projection operators
<a name="mongo-apis-query"></a>

**Topics**
+ [Array Operators](#mongo-apis-query-array-operators)
+ [Bitwise operators](#mongo-apis-query-bitwise-operators)
+ [Comment operator](#mongo-apis-query-comment-operator)
+ [Comparison operators](#mongo-apis-query-comparison-operators)
+ [Element operators](#mongo-apis-query-element-operators)
+ [Evaluation query operators](#mongo-apis-query-evaluation-operators)
+ [Logical operators](#mongo-apis-query-logical-operators)
+ [Projection operators](#mongo-apis-projection-operators)

### Array Operators
<a name="mongo-apis-query-array-operators"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1all](all.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1elemMatch](elemMatch.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1size](size-query.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Bitwise operators
<a name="mongo-apis-query-bitwise-operators"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1bitsAllSet](bitsAllSet.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1bitsAnySet](bitsAnySet.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1bitsAllClear](bitsAllClear.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1bitsAnyClear](bitsAnyClear.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Comment operator
<a name="mongo-apis-query-comment-operator"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1comment](comment.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Comparison operators
<a name="mongo-apis-query-comparison-operators"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1eq](eq.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1gt](gt.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1gte](gte.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1in](in.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1lt](lt.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1lte](lte.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1ne](ne.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1nin](nin.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Element operators
<a name="mongo-apis-query-element-operators"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1exists](exists.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1type](type.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Evaluation query operators
<a name="mongo-apis-query-evaluation-operators"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1expr](expr.md)  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  [\$1jsonSchema](jsonSchema.md)  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  [\$1mod](mod-query.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1regex](regex.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1text](text.md)  |  No  |  No  |  Yes  |  Yes  |  No  | 
|  \$1where  |  No  |  No  |  No  |  No  |  No  | 

### Logical operators
<a name="mongo-apis-query-logical-operators"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1and](and.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1nor](nor.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1not](not.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1or](or.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Projection operators
<a name="mongo-apis-projection-operators"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1](dollar-projection.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1elemMatch](elemMatch.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1meta](meta.md)  |  No  |  No  |  Yes  |  Yes  |  No  | 
|  [\$1slice](slice-projection.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

## Update operators
<a name="mongo-apis-update"></a>

**Topics**
+ [Array operators](#mongo-apis-update-array)
+ [Bitwise operators](#mongo-apis-update-bitwise)
+ [Field operators](#mongo-apis-update-field)
+ [Update modifiers](#mongo-apis-update-modifiers)

### Array operators
<a name="mongo-apis-update-array"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1](dollar-update.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1[]](dollarBrackets-update.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1[<identifier>]](dollarIdentifier-update.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1addToSet](addToSet.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1pop](pop.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1pullAll](pullAll.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1pull](pull.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1push](push.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Bitwise operators
<a name="mongo-apis-update-bitwise"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1bit](bit.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Field operators
<a name="mongo-apis-update-field"></a>


| Operator | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1currentDate](currentDate.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1inc](inc.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1max](max-update.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1min](min-update.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1mul](mul.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1rename](rename.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1set](set-update.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1setOnInsert](setOnInsert.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1unset](unset-update.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Update modifiers
<a name="mongo-apis-update-modifiers"></a>


| Operator | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1each](each.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1position](position.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1slice](slice-update.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1sort](sort-update.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

## Geospatial
<a name="mongo-apis-geospatial"></a>

### Geometry specifiers
<a name="mongo-apis-geospatial-geometry-specifiers"></a>


| Query Selectors | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  \$1box  |  No  |  No  |  No  |  No  |  No  | 
|  \$1center  |  No  |  No  |  No  |  No  |  No  | 
|  \$1centerSphere  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1geometry](geometry.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1maxDistance](maxDistance.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1minDistance](minDistance.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1nearSphere](nearSphere.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1polygon  |  No  |  No  |  No  |  No  |  No  | 
|  \$1uniqueDocs  |  No  |  No  |  No  |  No  |  No  | 

### Query selectors
<a name="mongo-apis-geospatial-query-selectors"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1geoIntersects](geoIntersects.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1geoWithin](geoWithin.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1near](near.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1nearSphere](nearSphere.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1polygon  |  No  |  No  |  No  |  No  |  No  | 
|  \$1uniqueDocs  |  No  |  No  |  No  |  No  |  No  | 

## Cursor methods
<a name="mongo-apis-cursor"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  cursor.batchSize()  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  cursor.close()  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  cursor.collation()  |  No  |  No  |  No  |  Yes  |  No  | 
|  cursor.comment()  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  cursor.count()  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  cursor.explain()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.forEach()  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  cursor.hasNext()  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  cursor.hint()  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes\$1  | 
|  cursor.isClosed()  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  cursor.isExhausted()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.itcount()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.limit()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.map()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.max()  |  No  |  No  |  No  |  No  |  No  | 
|  cursor.maxScan()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.maxTimeMS()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.min()  |  No  |  No  |  No  |  No  |  No  | 
|  cursor.next()  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  cursor.noCursorTimeout()  |  No  |  No  |  No  |  No  |  No  | 
|  cursor.objsLeftInBatch()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.pretty()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.readConcern()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.readPref()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.returnKey()  |  No  |  No  |  No  |  No  |  No  | 
|  cursor.showRecordId()  |  No  |  No  |  No  |  No  |  No  | 
|  cursor.size()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.skip()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.sort()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  cursor.tailable()  |  No  |  No  |  No  |  No  |  No  | 
|  cursor.toArray()  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 

\$1 Index `hint` is supported with index expressions. For example, `db.foo.find().hint({x:1})`.

## Aggregation pipeline operators
<a name="mongo-apis-aggregation-pipeline"></a>

**Topics**
+ [Accumulator expressions](#mongo-apis-aggregation-pipeline-accumulator-expressions)
+ [Arithmetic operators](#mongo-apis-aggregation-pipeline-arithmetic)
+ [Array operators](#mongo-apis-aggregation-pipeline-array)
+ [Boolean operators](#mongo-apis-aggregation-pipeline-boolean)
+ [Comparison operators](#mongo-apis-aggregation-pipeline-comparison)
+ [Conditional expression operators](#mongo-apis-aggregation-pipeline-conditional)
+ [Data type operator](#mongo-apis-aggregation-pipeline-data-type)
+ [Data size operator](#mongo-apis-aggregation-pipeline-data-size)
+ [Date operators](#mongo-apis-aggregation-pipeline-date)
+ [Literal operator](#mongo-apis-aggregation-pipeline-literal)
+ [Merge operator](#mongo-apis-aggregation-pipeline-merge)
+ [Natural operator](#mongo-apis-aggregation-pipeline-natural)
+ [Set operators](#mongo-apis-aggregation-pipeline-set)
+ [Stage operators](#mongo-apis-aggregation-pipeline-stage)
+ [String operators](#mongo-apis-aggregation-pipeline-string)
+ [System variables](#mongo-apis-aggregation-pipeline-system-variables)
+ [Text search operator](#mongo-apis-aggregation-pipeline-text-search)
+ [Type conversion operators](#mongo-apis-aggregation-pipeline-type)
+ [Variable operators](#mongo-apis-aggregation-pipeline-variable)
+ [Miscellaneous operators](#mongo-apis-aggregation-pipeline-misc)

### Accumulator expressions
<a name="mongo-apis-aggregation-pipeline-accumulator-expressions"></a>


| Expression | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  \$1accumulator  |  -  |  -  |  No  |  No  |  No  | 
|  [\$1addToSet](addToSet-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1avg](avg.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1count](count.md)  |  -  |  -  |  No  |  No  |  No  | 
|  \$1covariancePop  |  No  |  No  |  No  |  No  |  No  | 
|  \$1covarianceSamp  |  No  |  No  |  No  |  No  |  No  | 
|  \$1denseRank  |  No  |  No  |  No  |  No  |  No  | 
|  \$1derivative  |  No  |  No  |  No  |  No  |  No  | 
|  \$1documentNumber  |  No  |  No  |  No  |  No  |  No  | 
|  \$1expMovingAvg  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1first](first.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1integral  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1last](last.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1max](max.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1min](min.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1push](push-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1rank  |  No  |  No  |  No  |  No  |  No  | 
|  \$1shift  |  No  |  No  |  No  |  No  |  No  | 
|  \$1stdDevPop  |  No  |  No  |  No  |  No  |  No  | 
|  \$1stdDevSamp  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1sum](sum.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Arithmetic operators
<a name="mongo-apis-aggregation-pipeline-arithmetic"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1abs](abs.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1add](add.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1ceil](ceil.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1divide](divide.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1exp](exp.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1floor](floor.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1ln](ln.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1log](log.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1log10](log10.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1mod](mod.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1multiply](multiply.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1pow](pow.md)  |  No  |  No  |  No  |  Yes  |  No  | 
|  \$1round  |  -  |  -  |  No  |  No  |  No  | 
|  [\$1sqrt](sqrt.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1subtract](subtract.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1trunc  |  No  |  No  |  No  |  No  |  No  | 

### Array operators
<a name="mongo-apis-aggregation-pipeline-array"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1arrayElemAt](arrayElemAt.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1arrayToObject](arrayToObject.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1concatArrays](concatArrays.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1filter](filter.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1first](first.md)  |  -  |  -  |  Yes  |  Yes  |  No  | 
|  [\$1in](in-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1indexOfArray](indexOfArray.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1isArray](isArray.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1last](last.md)  |  -  |  -  |  Yes  |  Yes  |  No  | 
|  [\$1objectToArray](objectToArray.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1range](range.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1reverseArray](reverseArray.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1reduce](reduce.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1size](size.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1slice](slice.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1zip](zip.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Boolean operators
<a name="mongo-apis-aggregation-pipeline-boolean"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1and](and-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1not](not-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1or](or-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Comparison operators
<a name="mongo-apis-aggregation-pipeline-comparison"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1cmp](cmp.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1eq](eq-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1gt](gt-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1gte](gte-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1lt](lt-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1lte](lte-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1ne](ne-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Conditional expression operators
<a name="mongo-apis-aggregation-pipeline-conditional"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1cond](cond.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1ifNull](ifNull.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1switch](switch.md)  |  No  |  Yes  |  Yes  |  Yes  |  No  | 

### Data type operator
<a name="mongo-apis-aggregation-pipeline-data-type"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1type](type-aggregation.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Data size operator
<a name="mongo-apis-aggregation-pipeline-data-size"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  \$1binarySize  |  -  |  -  |  No  |  No  |  No  | 
|  \$1bsonSize  |  -  |  -  |  No  |  No  |  No  | 

### Date operators
<a name="mongo-apis-aggregation-pipeline-date"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1dateAdd](dateAdd.md)  |  No  |  No  |  Yes  |  Yes  |  Yes  | 
|  [\$1dateDiff](dateDiff.md)  |  -  |  -  |  Yes  |  Yes  |  No  | 
|  \$1dateFromParts  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1dateFromString](dateFromString.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1dateSubtract](dateSubtract.md)  |  No  |  No  |  Yes  |  Yes  |  Yes  | 
|  \$1dateToParts  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1dateToString](dateToString.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1dateTrunc](dateTrunc.md)  |  -  |  -  |  No  |  Yes  |  No  | 
|  [\$1dayOfMonth](dayOfMonth.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1dayOfWeek](dayOfWeek.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1dayOfYear](dayOfYear.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1hour](hour.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1isoDayOfWeek](isoDayOfWeek.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1isoWeek](isoWeek.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1isoWeekYear](isoWeekYear.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1millisecond](millisecond.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1minute](minute.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1month](month.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1second](second.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1week](week.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1year](year.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Literal operator
<a name="mongo-apis-aggregation-pipeline-literal"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1literal](literal.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Merge operator
<a name="mongo-apis-aggregation-pipeline-merge"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1mergeObjects](mergeObjects.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Natural operator
<a name="mongo-apis-aggregation-pipeline-natural"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1natural](natural.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Set operators
<a name="mongo-apis-aggregation-pipeline-set"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1allElementsTrue](allElementsTrue.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1anyElementTrue](anyElementTrue.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1setDifference](setDifference.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1setEquals](setEquals.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1setIntersection](setIntersection.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1setIsSubset](setIsSubset.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1setUnion](setUnion.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1setWindowFields  |  No  |  No  |  No  |  No  |  No  | 

### Stage operators
<a name="mongo-apis-aggregation-pipeline-stage"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1addFields](addFields.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1bucket](bucket.md)  |  No  |  No  |  No  |  Yes  |  No  | 
|  \$1bucketAuto  |  No  |  No  |  No  |  No  | 
|  [\$1changeStream](changeStream.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  [\$1collStats](collStats.md)  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  [\$1count](count.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1currentOp](currentOp.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1facet  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1geoNear](geoNear.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1graphLookup  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1group](group.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1indexStats](indexStats.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1limit](limit.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1listLocalSessions  |  No  |  No  |  No  |  No  |  No  | 
|  \$1listSessions  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1lookup](lookup.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1match](match.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1merge](merge.md)  |  -  |  -  |  No  |  Yes  |  No  | 
|  [\$1out](out.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  No  | 
|  \$1planCacheStats  |  -  |  -  |  No  |  No  |  No  | 
|  [\$1project](project.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1redact](redact.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1replaceRoot](replaceRoot.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1sample](sample.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1set](set-stage.md)  |  -  |  -  |  No  |  Yes  |  No  | 
|  \$1setWindowFields  |  -  |  -  |  No  |  No  |  No  | 
|  [\$1skip](skip.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1sort](sort.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1sortByCount  |  No  |  No  |  No  |  No  |  No  | 
|  \$1unionWith  |  -  |  -  |  No  |  No  |  No  | 
|  [\$1unset](unset-stage.md)  |  -  |  -  |  No  |  Yes  |  No  | 
|  [\$1unwind](unwind.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1replaceWith](replaceWith.md)  |  No  |  No  |  No  |  Yes  |  No  | 
|  [\$1vectorSearch](vectorSearch.md)  |  No  |  No  |  No  |  Yes  |  No  | 

### String operators
<a name="mongo-apis-aggregation-pipeline-string"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1concat](concat.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1indexOfBytes](indexOfBytes.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1indexOfCP](indexOfCP.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1ltrim](ltrim.md)  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  [\$1regexFind](regexFind.md)  |  -  |  -  |  Yes  |  Yes  |  No  | 
|  [\$1regexFindAll](regexFindAll.md)  |  -  |  -  |  Yes  |  Yes  |  No  | 
|  [\$1regexMatch](regexMatch.md)  |  -  |  -  |  Yes  |  Yes  |  No  | 
|  [\$1replaceAll](replaceAll.md)  |  -  |  -  |  Yes  |  Yes  |  No  | 
|  [\$1replaceOne](replaceOne.md)  |  -  |  -  |  Yes  |  Yes  |  No  | 
|  [\$1rtrim](rtrim.md)  |  No  |  Yes  |  Yes  |  Yes  |  No  | 
|  [\$1split](split.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1strcasecmp](strcasecmp.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1strLenBytes](strLenBytes.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1strLenCP](strLenCP.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1substr](substr.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1substrBytes](substrBytes.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1substrCP](substrCP.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1toLower](toLower.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1toUpper](toUpper.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1trim](trim.md)  |  No  |  Yes  |  Yes  |  Yes  |  No  | 

### System variables
<a name="mongo-apis-aggregation-pipeline-system-variables"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  \$1\$1CURRENT  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1\$1DESCEND](DESCEND.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1\$1KEEP](KEEP.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1\$1PRUNE](PRUNE.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1\$1REMOVE  |  No  |  No  |  No  |  No  |  No  | 
|  [\$1ROOT](ROOT.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Text search operator
<a name="mongo-apis-aggregation-pipeline-text-search"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1meta](meta-aggregation.md)  |  No  |  No  |  Yes  |  Yes  |  No  | 
|  [\$1search](search.md)  |  No  |  No  |  Yes  |  Yes  |  No  | 

### Type conversion operators
<a name="mongo-apis-aggregation-pipeline-type"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1convert](convert.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  \$1isNumber  |  -  |  -  |  No  |  No  |  No  | 
|  [\$1toBool](toBool.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1toDate](toDate.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1toDecimal](toDecimal.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1toDouble](toDouble.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1toInt](toInt.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1toLong](toLong.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1toObjectId](toObjectId.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1toString](toString.md)  |  No  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Variable operators
<a name="mongo-apis-aggregation-pipeline-variable"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1let](let.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  [\$1map](map.md)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 

### Miscellaneous operators
<a name="mongo-apis-aggregation-pipeline-misc"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  \$1getField  |  -  |  -  |  No  |  No  |  No  | 
|  [\$1rand](rand.md)  |  -  |  -  |  No  |  Yes  |  No  | 
|  \$1sampleRate  |  -  |  -  |  No  |  No  |  No  | 

## Data types
<a name="mongo-apis-data-types"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  32-bit Integer (int)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  64-bit Integer (long)  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Array  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Binary Data  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Boolean  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Date  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  DBPointer  |  No  |  No  |  No  |  No  |  No  | 
|  DBRefs  |  No  |  No  |  No  |  No  |  No  | 
|  Decimal128  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Double  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  JavaScript  |  No  |  No  |  No  |  No  |  No  | 
|  JavaScript (with scope)  |  No  |  No  |  No  |  No  |  No  | 
|  MaxKey  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  MinKey  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Null  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Object  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  ObjectId  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Regular Expression  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  String  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Symbol  |  No  |  No  |  No  |  No  |  No  | 
|  Timestamp  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Undefined  |  No  |  No  |  No  |  No  |  No  | 

## Indexes and index properties
<a name="mongo-apis-index"></a>

**Topics**
+ [Indexes](#mongo-apis-indexes)
+ [Index properties](#mongo-apis-index-properties)

### Indexes
<a name="mongo-apis-indexes"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  2dsphere  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  2d Index  |  No  |  No  |  No  |  No  |  No  | 
|  Compound Index  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Hashed Index  |  No  |  No  |  No  |  No  |  No  | 
|  Multikey Index  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Single Field Index  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Text Index  |  No  |  No  |  Yes  |  Yes  |  No  | 
|  Wildcard  |  No  |  No  |  No  |  No  |  No  | 

### Index properties
<a name="mongo-apis-index-properties"></a>


| Command | 3.6 | 4.0 | 5.0 | 8.0 | Elastic cluster | 
| --- | --- | --- | --- | --- | --- | 
|  Background  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Case Insensitive  |  No  |  No  |  No  |  Yes  |  No  | 
|  Hidden  |  No  |  No  |  No  |  No  |  No  | 
|  Partial  |  No  |  No  |  Yes  |  Yes  |  No  | 
|  Sparse  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Text  |  No  |  No  |  Yes  |  Yes  |  No  | 
|  TTL  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Unique  |  Yes  |  Yes  |  Yes  |  Yes  |  Yes  | 
|  Vector  |  No  |  No  |  Yes  |  Yes  |  No  | 

For detailed information about specific MongoDB operators, see the following topics:
+ [Aggregation pipeline operators](mongo-apis-aggregation-pipeline-operators.md)
+ [Geospatial](mongo-apis-geospatial-operators.md)
+ [Projection operators](#mongo-apis-projection-operators)
+ [Update operators](mongo-apis-update-operators.md)

# Aggregation pipeline operators
<a name="mongo-apis-aggregation-pipeline-operators"></a>

This section provides detailed information about aggregation pipeline operators supported by Amazon DocumentDB.

**Topics**
+ [\$1\$1DESCEND](DESCEND.md)
+ [\$1\$1KEEP](KEEP.md)
+ [\$1\$1PRUNE](PRUNE.md)
+ [\$1ROOT](ROOT.md)
+ [\$1abs](abs.md)
+ [\$1add](add.md)
+ [\$1addToSet](addToSet-aggregation.md)
+ [\$1addFields](addFields.md)
+ [\$1allElementsTrue](allElementsTrue.md)
+ [\$1and](and-aggregation.md)
+ [\$1anyElementTrue](anyElementTrue.md)
+ [\$1arrayElemAt](arrayElemAt.md)
+ [\$1arrayToObject](arrayToObject.md)
+ [\$1avg](avg.md)
+ [\$1bucket](bucket.md)
+ [\$1ceil](ceil.md)
+ [\$1changeStream](changeStream.md)
+ [\$1cmp](cmp.md)
+ [\$1collStats](collStats.md)
+ [\$1concat](concat.md)
+ [\$1concatArrays](concatArrays.md)
+ [\$1cond](cond.md)
+ [\$1convert](convert.md)
+ [\$1count](count.md)
+ [\$1currentOp](currentOp.md)
+ [\$1dateAdd](dateAdd.md)
+ [\$1dateDiff](dateDiff.md)
+ [\$1dateFromString](dateFromString.md)
+ [\$1dateSubtract](dateSubtract.md)
+ [\$1dateToString](dateToString.md)
+ [\$1dateTrunc](dateTrunc.md)
+ [\$1dayOfMonth](dayOfMonth.md)
+ [\$1dayOfWeek](dayOfWeek.md)
+ [\$1dayOfYear](dayOfYear.md)
+ [\$1divide](divide.md)
+ [\$1eq](eq-aggregation.md)
+ [\$1exp](exp.md)
+ [\$1filter](filter.md)
+ [\$1first](first.md)
+ [\$1floor](floor.md)
+ [\$1geoNear](geoNear.md)
+ [\$1group](group.md)
+ [\$1gt](gt-aggregation.md)
+ [\$1gte](gte-aggregation.md)
+ [\$1hour](hour.md)
+ [\$1ifNull](ifNull.md)
+ [\$1in](in-aggregation.md)
+ [\$1indexOfArray](indexOfArray.md)
+ [\$1indexOfBytes](indexOfBytes.md)
+ [\$1indexOfCP](indexOfCP.md)
+ [\$1indexStats](indexStats.md)
+ [\$1isArray](isArray.md)
+ [\$1isoDayOfWeek](isoDayOfWeek.md)
+ [\$1isoWeek](isoWeek.md)
+ [\$1isoWeekYear](isoWeekYear.md)
+ [\$1last](last.md)
+ [\$1let](let.md)
+ [\$1limit](limit.md)
+ [\$1literal](literal.md)
+ [\$1ln](ln.md)
+ [\$1log](log.md)
+ [\$1log10](log10.md)
+ [\$1lt](lt-aggregation.md)
+ [\$1lte](lte-aggregation.md)
+ [\$1lookup](lookup.md)
+ [\$1ltrim](ltrim.md)
+ [\$1map](map.md)
+ [\$1match](match.md)
+ [\$1max](max.md)
+ [\$1meta](meta-aggregation.md)
+ [\$1merge](merge.md)
+ [\$1mergeObjects](mergeObjects.md)
+ [\$1millisecond](millisecond.md)
+ [\$1min](min.md)
+ [\$1minute](minute.md)
+ [\$1mod](mod.md)
+ [\$1month](month.md)
+ [\$1multiply](multiply.md)
+ [\$1natural](natural.md)
+ [\$1ne](ne-aggregation.md)
+ [\$1not](not-aggregation.md)
+ [\$1objectToArray](objectToArray.md)
+ [\$1or](or-aggregation.md)
+ [\$1out](out.md)
+ [\$1pow](pow.md)
+ [\$1push](push-aggregation.md)
+ [\$1project](project.md)
+ [\$1rand](rand.md)
+ [\$1range](range.md)
+ [\$1redact](redact.md)
+ [\$1reduce](reduce.md)
+ [\$1regexFind](regexFind.md)
+ [\$1regexFindAll](regexFindAll.md)
+ [\$1regexMatch](regexMatch.md)
+ [\$1replaceAll](replaceAll.md)
+ [\$1replaceOne](replaceOne.md)
+ [\$1replaceRoot](replaceRoot.md)
+ [\$1replaceWith](replaceWith.md)
+ [\$1reverseArray](reverseArray.md)
+ [\$1rtrim](rtrim.md)
+ [\$1sample](sample.md)
+ [\$1search](search.md)
+ [\$1second](second.md)
+ [\$1set](set-stage.md)
+ [\$1setDifference](setDifference.md)
+ [\$1setEquals](setEquals.md)
+ [\$1setIntersection](setIntersection.md)
+ [\$1setIsSubset](setIsSubset.md)
+ [\$1setUnion](setUnion.md)
+ [\$1skip](skip.md)
+ [\$1slice](slice.md)
+ [\$1size](size.md)
+ [\$1sort](sort.md)
+ [\$1split](split.md)
+ [\$1sqrt](sqrt.md)
+ [\$1strLenBytes](strLenBytes.md)
+ [\$1strLenCP](strLenCP.md)
+ [\$1strcasecmp](strcasecmp.md)
+ [\$1substr](substr.md)
+ [\$1substrBytes](substrBytes.md)
+ [\$1substrCP](substrCP.md)
+ [\$1subtract](subtract.md)
+ [\$1sum](sum.md)
+ [\$1switch](switch.md)
+ [\$1toBool](toBool.md)
+ [\$1toDate](toDate.md)
+ [\$1toDecimal](toDecimal.md)
+ [\$1toDouble](toDouble.md)
+ [\$1toInt](toInt.md)
+ [\$1toLong](toLong.md)
+ [\$1toLower](toLower.md)
+ [\$1toObjectId](toObjectId.md)
+ [\$1toString](toString.md)
+ [\$1toUpper](toUpper.md)
+ [\$1trim](trim.md)
+ [\$1type](type-aggregation.md)
+ [\$1unset](unset-stage.md)
+ [\$1unwind](unwind.md)
+ [\$1vectorSearch](vectorSearch.md)
+ [\$1week](week.md)
+ [\$1year](year.md)
+ [\$1zip](zip.md)

# \$1\$1DESCEND
<a name="DESCEND"></a>

The `$$DESCEND` operator in Amazon DocumentDB is a special positional array operator used within the `$redact` pipeline stage. It instructs the aggregation pipeline to descend into the current document and process all fields, regardless of their nesting level.

When the `$redact` stage encounters the `$$DESCEND` operator, it will keep all the fields in the current document visible and process them further down the pipeline. This is useful when you want to selectively redact or prune certain fields based on a condition, while retaining the structure of the document.

**Parameters**

None.

## Example (MongoDB Shell)
<a name="DESCEND-examples"></a>

In this example, we'll use the `$redact` stage with the `$$DESCEND` operator to selectively display documents where the `code` field is equal to "Reg".

**Create sample documents**

```
db.patient.insertMany([
  { "_id": 1, "code": "Emp", "patient": "John Doe", "DOB": "1/1/1980", "Hospital": "Main" },
  { "_id": 2, "code": "Reg", "patient": "Jane Doe", "DOB": "3/27/1989", "Hospital": "Cherry Hill" },
  { "_id": 3, "code": "Emp", "patient": "Bob Smith", "DOB": "6/15/1975", "Hospital": "Downtown" }
]);
```

**Query example**

```
db.patient.aggregate([
  { $redact: {
    $cond: {
      if: { $eq: ["Reg", "$code"] },
      then: "$$DESCEND",
      else: "$$PRUNE"
    }
  }}
]);
```

**Output**

```
{
  "_id": 2,
  "code": "Reg",
  "patient": "Jane Doe",
  "DOB": "3/27/1989",
  "Hospital": "Cherry Hill"
}
```

## Code examples
<a name="DESCEND-code"></a>

To view a code example for using the `$$DESCEND` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function redactPatients() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('patient');

  const result = await collection.aggregate([
    { $redact: {
      $cond: {
        if: { $eq: ["Reg", "$code"] },
        then: "$$DESCEND",
        else: "$$PRUNE"
      }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

redactPatients();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def redact_patients():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.patient

    result = list(collection.aggregate([
        { "$redact": {
            "$cond": {
                "if": { "$eq": ["Reg", "$code"] },
                "then": "$$DESCEND",
                "else": "$$PRUNE"
            }
        }}
    ]))

    print(result)
    client.close()

redact_patients()
```

------

# \$1\$1KEEP
<a name="KEEP"></a>

The `$$KEEP` system variable is used with the `$redact` stage in the aggregation pipeline to keep the current document or field unchanged and include it in the output.

**Parameters**

None

## Example (MongoDB Shell)
<a name="KEEP-examples"></a>

The following example demonstrates the usage of `$$KEEP` in an Amazon DocumentDB aggregation pipeline. Documents are only kept if access equals "public", otherwise they are removed.

**Create sample documents**

```
db.articles.insertMany([
  { title: "Article A", access: "public", content: "Visible content" },
  { title: "Article B", access: "private", content: "Hidden content" }
]);
```

**Query example**

```
db.articles.aggregate([
  {
    $redact: {
      $cond: [
        { $eq: ["$access", "public"] },
        "$$KEEP",
        "$$PRUNE"
      ]
    }
  }
]);
```

**Output**

```
[
  {
    "_id" : ObjectId("..."),
    "title" : "Article A",
    "access" : "public",
    "content" : "Visible content"
  }
]
```

## Code examples
<a name="KEEP-code"></a>

To view a code example for using the `$$KEEP` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function run() {
  const client = new MongoClient(
    'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0'
  );

  try {
    await client.connect();
    const db = client.db('test');
    const articles = db.collection('articles');

    const pipeline = [
      {
        $redact: {
          $cond: [
            { $eq: ["$access", "public"] },
            "$$KEEP",
            "$$PRUNE"
          ]
        }
      }
    ];

    const results = await articles.aggregate(pipeline).toArray();
    console.log(results);
  } finally {
    await client.close();
  }
}

run().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient(
    "mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0"
)

db = client.test
articles = db.articles

pipeline = [
    {
        "$redact": {
            "$cond": [
                {"$eq": ["$access", "public"]},
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
]

results = list(articles.aggregate(pipeline))
print(results)

client.close()
```

------

# \$1\$1PRUNE
<a name="PRUNE"></a>

The `$$PRUNE` system variable is used with the `$redact` stage in the aggregation pipeline to exclude documents or embedded document levels from the results. When a condition evaluates to `$$PRUNE`, the current document or subdocument is removed from the output. It is typically used with `$$DESCEND` (to keep and traverse the document) or `$$KEEP` (to keep the document at all levels).

**Parameters**

None. The `$$PRUNE` system variable is used without any parameters and must be used with `$redact`.

## Example (MongoDB Shell)
<a name="PRUNE-examples"></a>

The following example demonstrates how to use `$$PRUNE` with `$redact` to exclude users over 30 years old from the results.

**Create sample documents**

```
db.users.insert([
  { _id:1, name: "Carlos Salazar", age: 35, address: { street: "123 Main St", city: "Anytown", state: "CA" } },
  { _id:2, name: "Saanvi Sarkar", age: 28, address: { street: "456 Oak Rd", city: "Someplace", state: "NY" } },
  { _id:3, name: "Li Juan", age: 42, address: { street: "789 Pine Ave", city: "Springfield", state: "TX" } }
])
```

**Query example**

```
db.users.aggregate([
  {
    $redact: {
      $cond: {
        if: { $gt: ["$age", 30] },
        then: "$$PRUNE",
        else: "$$DESCEND"
      }
    }
  }
])
```

**Output**

```
[
  {
    "_id": 2,
    "name": "Saanvi Sarkar",
    "age": 28,
    "address": {
      "street": "456 Oak Rd",
      "city": "Someplace",
      "state": "NY"
    }
  }
]
```

## Code examples
<a name="PRUNE-code"></a>

To view a code example for using the `$$PRUNE` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

async function main() {
  await client.connect();
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([
    {
      $redact: {
        $cond: {
          if: { $gt: ["$age", 30] },
          then: "$$PRUNE",
          else: "$$DESCEND"
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']

result = list(users.aggregate([
    {
        '$redact': {
            '$cond': {
                'if': { '$gt': ['$age', 30] },
                'then': '$$PRUNE',
                'else': '$$DESCEND'
            }
        }
    }
]))

print(result)
client.close()
```

------

# \$1ROOT
<a name="ROOT"></a>

The `$ROOT` operator in Amazon DocumentDB is used to reference the entire input document within an aggregation pipeline. It allows you to access and manipulate the complete document, including all its nested fields and structures.

**Parameters**

None

## Example (MongoDB Shell)
<a name="ROOT-examples"></a>

This example demonstrates using `$ROOT` to create an audit log that captures the complete original document along with metadata about when it was processed.

**Create sample documents**

```
db.orders.insertMany([
  {
    _id: 1,
    orderId: "ORD-2024-001",
    customer: "María García",
    email: "maría@example.com",
    items: [
      { product: "Laptop", quantity: 1, price: 1299.99 }
    ],
    totalAmount: 1299.99
  },
  {
    _id: 2,
    orderId: "ORD-2024-002",
    customer: "Arnav Desai",
    email: "arnav@example.com",
    items: [
      { product: "Mouse", quantity: 2, price: 29.99 },
      { product: "Keyboard", quantity: 1, price: 89.99 }
    ],
    totalAmount: 149.97
  }
]);
```

**Query example**

```
db.orders.aggregate([
  {
    $project: {
      processedAt: new Date(),
      originalDocument: "$$ROOT",
      summary: {
        $concat: [
          "Order ",
          "$orderId",
          " for ",
          "$customer",
          " - Total: $",
          { $toString: "$totalAmount" }
        ]
      }
    }
  }
]);
```

**Output**

```
[
  {
    _id: 1,
    processedAt: ISODate('2025-11-24T20:43:51.492Z'),
    originalDocument: {
      _id: 1,
      orderId: 'ORD-2024-001',
      customer: 'María García',
      email: 'maría@example.com',
      items: [ { product: 'Laptop', quantity: 1, price: 1299.99 } ],
      totalAmount: 1299.99
    },
    summary: 'Order ORD-2024-001 for María García - Total: $1299.99'
  },
  {
    _id: 2,
    processedAt: ISODate('2025-11-24T20:43:51.492Z'),
    originalDocument: {
      _id: 2,
      orderId: 'ORD-2024-002',
      customer: 'Arnav Desai',
      email: 'arnav@example.com',
      items: [
        { product: 'Mouse', quantity: 2, price: 29.99 },
        { product: 'Keyboard', quantity: 1, price: 89.99 }
      ],
      totalAmount: 149.97
    },
    summary: 'Order ORD-2024-002 for Arnav Desai - Total: $149.97'
  }
]
```

## Code examples
<a name="ROOT-code"></a>

To view a code example for using the `$ROOT` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function createAuditLog() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const orders = db.collection('orders');

  const result = await orders.aggregate([
    {
      $project: {
        processedAt: new Date(),
        originalDocument: "$$ROOT",
        summary: {
          $concat: [
            "Order ",
            "$orderId",
            " for ",
            "$customer",
            " - Total: $",
            { $toString: "$totalAmount" }
          ]
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

createAuditLog();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from datetime import datetime

def create_audit_log():
    client = MongoClient('mongodb://username:password@docdb-cluster.cluster-123456789.us-east-1.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.aggregate([
        {
            '$project': {
                'processedAt': datetime.now(),
                'originalDocument': '$$ROOT',
                'summary': {
                    '$concat': [
                        "Order ",
                        "$orderId",
                        " for ",
                        "$customer",
                        " - Total: $",
                        { '$toString': "$totalAmount" }
                    ]
                }
            }
        }
    ]))

    print(result)
    client.close()

create_audit_log()
```

------

# \$1abs
<a name="abs"></a>

The `$abs` operator in Amazon DocumentDB returns the absolute value of a number. It can be used in the aggregation pipeline to perform mathematical operations on numeric fields.

**Parameters**
+ `number`: The numeric expression for which the absolute value will be returned.

## Example (MongoDB Shell)
<a name="abs-examples"></a>

This example demonstrates the usage of the `$abs` operator to find the absolute value of a numeric field.

**Create sample documents**

```
db.numbers.insertMany([
  { "_id": 1, "value": -5 },
  { "_id": 2, "value": 10 },
  { "_id": 3, "value": -3.14 },
  { "_id": 4, "value": 0 }
]);
```

**Query example**

```
db.numbers.aggregate([
  { $project: {
    "_id": 1,
    "absolute_value": { $abs: "$value" }
  }}
]);
```

**Output**

```
[
  { "_id": 1, "absolute_value": 5 },
  { "_id": 2, "absolute_value": 10 },
  { "_id": 3, "absolute_value": 3.14 },
  { "_id": 4, "absolute_value": 0 }
]
```

## Code examples
<a name="abs-code"></a>

To view a code example for using the `$abs` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      "_id": 1,
      "absolute_value": { $abs: "$value" }
    }}
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        { '$project': {
            "_id": 1,
            "absolute_value": { "$abs": "$value" }
        }}
    ]))

    print(result)
    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1add
<a name="add"></a>

The `$add` operator in Amazon DocumentDB is used to add numbers or dates together. It can be used to perform arithmetic operations on numeric fields or to perform date arithmetic by adding a number of time units to a date field.

**Parameters**
+ `expression1`: The first number or date to add.
+ `expression2`: The second number or date to add.
+ `expression3`: (optional) Additional numbers or dates to add.

## Example (MongoDB Shell)
<a name="add-examples"></a>

The following example demonstrates how to use the `$add` operator to add two numbers together.

**Create sample documents**

```
db.numbers.insertMany([
  { _id: 1, a: 5, b: 3 },
  { _id: 2, a: 10, b: 7 },
  { _id: 3, a: 2, b: 8 }
]);
```

**Query example**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    sum: { $add: ["$a", "$b"] }
  }}
])
```

**Output**

```
[
  { "_id" : 1, "sum" : 8 },
  { "_id" : 2, "sum" : 17 },
  { "_id" : 3, "sum" : 10 }
]
```

In this example, the `$add` operator is used to add the values of the `a` and `b` fields for each document and store the result in the `sum` field.

## Code examples
<a name="add-code"></a>

To view a code example for using the `$add` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      _id: 1,
      sum: { $add: ['$a', '$b'] }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['numbers']

result = list(collection.aggregate([
    { '$project': {
        '_id': 1,
        'sum': { '$add': ['$a', '$b'] }
    }}
]))

print(result)
client.close()
```

------

# \$1addToSet
<a name="addToSet-aggregation"></a>

The `$addToSet` aggregation operator returns an array of unique values from a specified expression for each group. It is used within the `$group` stage to accumulate distinct values, automatically eliminating duplicates.

**Parameters**
+ `expression`: The expression to evaluate for each document in the group.

## Example (MongoDB Shell)
<a name="addToSet-aggregation-examples"></a>

The following example demonstrates using the `$addToSet` operator to collect unique cities where orders were placed for each customer.

**Create sample documents**

```
db.orders.insertMany([
  { _id: 1, customer: "Alice", city: "Seattle", amount: 100 },
  { _id: 2, customer: "Alice", city: "Portland", amount: 150 },
  { _id: 3, customer: "Bob", city: "Seattle", amount: 200 },
  { _id: 4, customer: "Alice", city: "Seattle", amount: 75 },
  { _id: 5, customer: "Bob", city: "Boston", amount: 300 }
]);
```

**Query example**

```
db.orders.aggregate([
  {
    $group: {
      _id: "$customer",
      cities: { $addToSet: "$city" }
    }
  }
]);
```

**Output**

```
[
  { _id: 'Bob', cities: [ 'Seattle', 'Boston' ] },
  { _id: 'Alice', cities: [ 'Seattle', 'Portland' ] }
]
```

## Code examples
<a name="addToSet-aggregation-code"></a>

To view a code example for using the `$addToSet` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $group: {
        _id: "$customer",
        cities: { $addToSet: "$city" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.aggregate([
        {
            '$group': {
                '_id': '$customer',
                'cities': { '$addToSet': '$city' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1addFields
<a name="addFields"></a>

The `$addFields` stage in the Amazon DocumentDB aggregation pipeline allows you to add new computed fields to documents. This can be useful for adding derived or transformed data to the documents.

**Parameters**
+ `newField`: The name of the new field to add.
+ `expression`: An expression that resolves to the value of the new field.

## Example (MongoDB Shell)
<a name="addFields-examples"></a>

The following example demonstrates how to use `$addFields` to add a new field `TotalInventory` that calculates the total inventory based on the `Inventory.OnHand` and `Inventory.OrderQnty` fields.

**Create sample documents**

```
db.example.insertMany([
  {
    "Item": "Spray Paint",
    "Colors": ["Black", "Red", "Green", "Blue"],
    "Inventory": {
      "OnHand": 47,
      "MinOnHand": 50,
      "OrderQnty": 36
    },
    "UnitPrice": 3.99
  },
  {
    "Item": "Ruler",
    "Colors": ["Red", "Green", "Blue", "Clear", "Yellow"],
    "Inventory": {
      "OnHand": 47,
      "MinOnHand": 40
    },
    "UnitPrice": 0.89
  }
]);
```

**Query example**

```
db.example.aggregate([
  {
    $addFields: {
      TotalInventory: { $add: ["$Inventory.OnHand", "$Inventory.OrderQnty"] }
    }
  }
])
```

**Output**

```
[
  {
    "_id" : ObjectId("5bedafbcf65ff161707de24f"),
    "Item" : "Ruler",
    "Colors" : [ "Red", "Green", "Blue", "Clear", "Yellow" ],
    "Inventory" : {
      "OnHand" : 47,
      "MinOnHand" : 40
    },
    "UnitPrice" : 0.89,
    "TotalInventory" : 47
  },
  {
    "_id" : ObjectId("5bedafbcf65ff161707de250"),
    "Item" : "Spray Paint",
    "Colors" : [ "Black", "Red", "Green", "Blue" ],
    "Inventory" : {
      "OnHand" : 47,
      "MinOnHand" : 50,
      "OrderQnty" : 36
    },
    "UnitPrice" : 3.99,
    "TotalInventory" : 83
  }
]
```

## Code examples
<a name="addFields-code"></a>

To view a code example for using the `$addFields` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const collection = db.collection('example');

const result = await collection.aggregate([
  {
    $addFields: {
      TotalInventory: { $add: ['$Inventory.OnHand', '$Inventory.OrderQnty'] }
    }
  }
]).toArray();

console.log(result);

await client.close();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['example']

result = list(collection.aggregate([
    {
        '$addFields': {
            'TotalInventory': { '$add': ['$Inventory.OnHand', '$Inventory.OrderQnty'] }
        }
    }
]))

print(result)
client.close()
```

------

# \$1allElementsTrue
<a name="allElementsTrue"></a>

New from version 4.0

The `$allElementsTrue` operator is used to check if all elements in an array evaluate to a true value.

**Parameters**
+ `expression`: An expression that evaluates to an array.

## Example (MongoDB Shell)
<a name="allElementsTrue-examples"></a>

The following example demonstrates the usage of `$allElementsTrue` to check if all elements in an array are true.

**Create sample documents**

```
db.collection.insert([
  { "name": "John", "scores": [100, 90, 80] },
  { "name": "Jane", "scores": [80, 85, 0] },
  { "name": "Bob", "scores": [90, 95, null] }
])
```

**Query example**

```
db.collection.find({
  "scores": { "$allElementsTrue": [{ "$gt": 0 }] }
})
```

**Output**

```
[
  { "_id" : ObjectId("..."), "name" : "John", "scores" : [ 100, 90, 80 ] },
  { "_id" : ObjectId("..."), "name" : "Bob", "scores" : [ 90, 95, null ] }
]
```

In this example, the query checks if all elements in the `scores` array are greater than 0. The document with `&quot;name&quot;: &quot;Jane&quot;` is excluded because the `scores` array contains a 0, which is a falsy value.

## Code examples
<a name="allElementsTrue-code"></a>

To view a code example for using the `$allElementsTrue` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.find({
    "scores": { "$allElementsTrue": [{ "$gt": 0 }] }
  }).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['collection']

    result = list(collection.find({
        "scores": {"$allElementsTrue": [{"$gt": 0}]}
    }))

    print(result)

    client.close()

example()
```

------

# \$1and
<a name="and-aggregation"></a>

The `$and` aggregation operator evaluates multiple expressions and returns `true` only if all expressions evaluate to `true`. If any expression is `false`, it returns `false`.

**Parameters**
+ `expressions`: An array of expressions to evaluate.

## Example (MongoDB Shell)
<a name="and-aggregation-examples"></a>

The following example demonstrates using the `$and` operator to check if products meet multiple criteria.

**Create sample documents**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", price: 1200, inStock: true },
  { _id: 2, name: "Mouse", price: 25, inStock: false },
  { _id: 3, name: "Keyboard", price: 75, inStock: true }
]);
```

**Query example**

```
db.products.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      inStock: 1,
      affordable: {
        $and: [
          { $lt: ["$price", 100] },
          { $eq: ["$inStock", true] }
        ]
      }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, name: 'Laptop', price: 1200, inStock: true, affordable: false },
  { _id: 2, name: 'Mouse', price: 25, inStock: false, affordable: false },
  { _id: 3, name: 'Keyboard', price: 75, inStock: true, affordable: true }
]
```

## Code examples
<a name="and-aggregation-code"></a>

To view a code example for using the `$and` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        price: 1,
        inStock: 1,
        affordable: {
          $and: [
            { $lt: ["$price", 100] },
            { $eq: ["$inStock", true] }
          ]
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'price': 1,
                'inStock': 1,
                'affordable': {
                    '$and': [
                        { '$lt': ['$price', 100] },
                        { '$eq': ['$inStock', True] }
                    ]
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1anyElementTrue
<a name="anyElementTrue"></a>

New from version 4.0

The `$anyElementTrue` operator is used to determine if any element in an array is true.

**Parameters**
+ `field`: An array field to evaluate.

## Example (MongoDB Shell)
<a name="anyElementTrue-examples"></a>

The following example demonstrates the usage of `$anyElementTrue` to check if any element in an array is true.

**Create sample documents**

```
db.grades.insertMany([
  { _id: 1, student: 'Tim', scores: [false, false, null] },
  { _id: 2, student: 'Bob', scores: [false, 0, false] },
  { _id: 3, student: 'Ivy', scores: [false, true, 0] }
])
```

**Query example**

```
db.grades.aggregate([
  {
    $project: {
      student: 1,
      isAnyTrue: { $anyElementTrue: ["$scores"] },
      _id: 0
    }
  }
])
```

**Output**

```
[
  { student: 'Tim', isAnyTrue: false },
  { student: 'Bob', isAnyTrue: false },
  { student: 'Ivy', isAnyTrue: true }
]
```

## Code examples
<a name="anyElementTrue-code"></a>

To view a code example for using the `$anyElementTrue` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('grades');

  const result = await collection.aggregate([
    {
      $project: {
        student: 1,
        isAnyTrue: { $anyElementTrue: ["$scores"] },
        _id: 0
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['grades']

    result = list(collection.aggregate([
      {
        "$project": {
          "student": 1,
          "isAnyTrue": { "$anyElementTrue": ["$scores"] },
          "_id": 0
        }
      }
    ]))

    print(result)

    client.close()

example()
```

------

# \$1arrayElemAt
<a name="arrayElemAt"></a>

The `$arrayElemAt` operator in Amazon DocumentDB allows you to retrieve an element from an array by its index position. This is particularly useful when you need to access a specific element within an array field in your documents.

**Parameters**
+ `array`: The input array from which an element is to be retrieved.
+ `index`: The zero-based index position of the element to retrieve. This value must be a non-negative integer.

## Example (MongoDB Shell)
<a name="arrayElemAt-examples"></a>

In this example, we'll demonstrate how to use the `$arrayElemAt` operator to retrieve specific elements from the `flight_miles` array in the `miles` collection.

**Create sample documents**

```
db.miles.insertMany([
  { "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ]},
  { "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 2560, 890, 2780 ]},
  { "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 880 ]}
]);
```

**Query example**

```
db.miles.aggregate([
  { $project: {
    "_id": 1,
    "first_mile": { $arrayElemAt: [ "$flight_miles", 0 ] },
    "last_mile": { $arrayElemAt: [ "$flight_miles", -1 ] }
  }}
]);
```

**Output**

```
{ "_id" : 1, "first_mile" : 1205, "last_mile" : 880 }
{ "_id" : 2, "first_mile" : 1205, "last_mile" : 2780 }
{ "_id" : 3, "first_mile" : 1205, "last_mile" : 880 }
```

In this example, we use the `$arrayElemAt` operator to retrieve the first and last elements of the `flight_miles` array for each document.

## Code examples
<a name="arrayElemAt-code"></a>

To view a code example for using the `$arrayElemAt` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  const result = await collection.aggregate([
    { $project: {
      "_id": 1,
      "first_mile": { $arrayElemAt: [ "$flight_miles", 0 ] },
      "last_mile": { $arrayElemAt: [ "$flight_miles", -1 ] }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.mydatabase
    collection = db.miles

    result = list(collection.aggregate([
        { "$project": {
            "_id": 1,
            "first_mile": { "$arrayElemAt": [ "$flight_miles", 0 ] },
            "last_mile": { "$arrayElemAt": [ "$flight_miles", -1 ] }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1arrayToObject
<a name="arrayToObject"></a>

The `$arrayToObject` operator in Amazon DocumentDB is the reverse of the `$objectToArray` operator. It takes an array of key-value pair documents and converts it into a single document. This is particularly useful when you need to convert an array of key-value pairs back into an object or document structure.

**Parameters**
+ `array expression`: An expression that resolves to an array. The array elements must be documents with two fields: `k` (the key) and `v` (the value).

## Example (MongoDB Shell)
<a name="arrayToObject-examples"></a>

The example below demonstrates how to use `$arrayToObject` to convert an array of key-value pairs back into a document.

**Create sample documents**

```
db.videos.insertMany([
  { "_id": 1, "name": "Live Soft", "inventory": { "Des Moines": 1000, "Ames": 500 } },
  { "_id": 2, "name": "Top Pilot", "inventory": { "Mason City": 250, "Des Moines": 1000 } },
  { "_id": 3, "name": "Romancing the Rock", "inventory": { "Mason City": 250, "Ames": 500 } },
  { "_id": 4, "name": "Bravemind", "inventory": { "Mason City": 250, "Des Moines": 1000, "Ames": 500 } }
]);
```

**Query example**

```
db.videos.aggregate([
  { $project: { name: 1, videos: { $objectToArray: "$inventory" } } },
  { $project: { name: 1, inventory: { $arrayToObject: "$videos" } } }
]);
```

**Output**

```
{ "_id" : 1, "name" : "Live Soft", "inventory" : { "Des Moines" : 1000, "Ames" : 500 } }
{ "_id" : 2, "name" : "Top Pilot", "inventory" : { "Mason City" : 250, "Des Moines" : 1000 } }
{ "_id" : 3, "name" : "Romancing the Rock", "inventory" : { "Mason City" : 250, "Ames" : 500 } }
{ "_id" : 4, "name" : "Bravemind", "inventory" : { "Mason City" : 250, "Des Moines" : 1000, "Ames" : 500 } }
```

In this example, the `$objectToArray` operator is used to convert the `inventory` object into an array of key-value pairs. The `$arrayToObject` operator is then used to convert the array back into a document, restoring the original object structure.

## Code examples
<a name="arrayToObject-code"></a>

To view a code example for using the `$arrayToObject` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('videos');

  const result = await collection.aggregate([
    { $project: { name: 1, videos: { $objectToArray: '$inventory' } } },
    { $project: { name: 1, inventory: { $arrayToObject: '$videos' } } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['videos']

    result = list(collection.aggregate([
        { '$project': { 'name': 1, 'videos': { '$objectToArray': '$inventory' } } },
        { '$project': { 'name': 1, 'inventory': { '$arrayToObject': '$videos' } } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1avg
<a name="avg"></a>

The `$avg` aggregation operator in Amazon DocumentDB calculates the average value of the specified expression across the documents that are input to the stage. This operator is useful for computing the average of a numeric field or expression across a set of documents.

**Parameters**
+ `expression`: The expression to use to calculate the average. This can be a field path (e.g. `"$field"`) or an expression (e.g. `{ $multiply: ["$field1", "$field2"] }`).

## Example (MongoDB Shell)
<a name="avg-examples"></a>

The following example demonstrates how to use the `$avg` operator to calculate the average score across a set of student documents.

**Create sample documents**

```
db.students.insertMany([
  { name: "John", score: 85 },
  { name: "Jane", score: 92 },
  { name: "Bob", score: 78 },
  { name: "Alice", score: 90 }
]);
```

**Query example**

```
db.students.aggregate([
  { $group: { 
    _id: null,
    avgScore: { $avg: "$score" }
  }}
]);
```

**Output**

```
[
  {
    "_id": null,
    "avgScore": 86.25
  }
]
```

## Code examples
<a name="avg-code"></a>

To view a code example for using the `$avg` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function calculateAvgScore() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const result = await db.collection('students').aggregate([
    { $group: {
      _id: null,
      avgScore: { $avg: '$score' }
    }}
  ]).toArray();
  console.log(result);
  await client.close();
}

calculateAvgScore();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def calculate_avg_score():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    result = list(db.students.aggregate([
        { '$group': {
            '_id': None,
            'avgScore': { '$avg': '$score' }
        }}
    ]))
    print(result)
    client.close()

calculate_avg_score()
```

------

# \$1bucket
<a name="bucket"></a>

New from version 8.0

Not supported by Elastic cluster.

The `$bucket` aggregation stage in Amazon DocumentDB allows you to group input documents into buckets based on a specified expression and bucket boundaries. This can be useful for analyzing data that falls within certain value ranges or categories.

**Parameters**
+ `groupBy` (required): The expression that specifies the value to group by.
+ `boundaries` (required): An array of double values that define the bucket boundaries. Documents are assigned to buckets based on the `groupBy` expression value falling within the specified boundaries.
+ `default` (optional): A literal value that is output for documents whose `groupBy` expression value does not fall into any of the specified boundaries.
+ `output` (optional): An object that specifies the information to output for each bucket. You can use accumulator operators like `$sum`, `$avg`, `$min`, and `$max` to compute aggregations for each bucket.

## Example (MongoDB Shell)
<a name="bucket-examples"></a>

The following example demonstrates how to use the `$bucket` stage to group sales data by price range.

**Create sample documents**

```
db.sales.insertMany([
  { item: "abc", price: 10, quantity: 2, date: new Date("2020-09-01") },
  { item: "def", price: 20, quantity: 1, date: new Date("2020-10-01") },
  { item: "ghi", price: 5, quantity: 3, date: new Date("2020-11-01") },
  { item: "jkl", price: 15, quantity: 2, date: new Date("2020-12-01") },
  { item: "mno", price: 25, quantity: 1, date: new Date("2021-01-01") }
]);
```

**Query example**

```
db.sales.aggregate([
  {
    $bucket: {
      groupBy: "$price",
      boundaries: [0, 10, 20, 30],
      default: "Other",
      output: {
        "count": { $sum: 1 },
        "totalQuantity": { $sum: "$quantity" }
      }
    }
  },
  {
    $sort: { _id: 1 }
  }
])
```

**Output**

```
[
  { _id: 0, count: 1, totalQuantity: 3 },
  { _id: 10, count: 2, totalQuantity: 4 },
  { _id: 20, count: 2, totalQuantity: 2 }
]
```

## Code examples
<a name="bucket-code"></a>

To view a code example for using the `$bucket` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const sales = db.collection('sales');

  const result = await sales.aggregate([
    {
      $bucket: {
        groupBy: "$price",
        boundaries: [0, 10, 20, 30],
        default: "Other",
        output: {
          "count": { $sum: 1 },
          "totalQuantity": { $sum: "$quantity" }
        }
      }
    },
    {
      $sort: { _id: 1 }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&lsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    sales = db['sales']

    result = list(sales.aggregate([
        {
            '$bucket': {
                'groupBy': '$price',
                'boundaries': [0, 10, 20, 30],
                'default': 'Other',
                'output': {
                    'count': {'$sum': 1},
                    'totalQuantity': {'$sum': '$quantity'}
                }
            }
        },
        {
            "$sort": { "_id": 1 }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1ceil
<a name="ceil"></a>

New from version 4.0

The `$ceil` operator in Amazon DocumentDB, as in MongoDB, rounds a number up to the nearest integer. This is useful when you need to perform mathematical operations on numeric fields and ensure the result is a whole number.

**Parameters**
+ `expression`: The numeric expression to round up.

## Example (MongoDB Shell)
<a name="ceil-examples"></a>

This example demonstrates how to use the `$ceil` operator to round up a numeric field.

**Create sample documents**

```
db.numbers.insertMany([
  { "_id": 1, "value": 3.14 },
  { "_id": 2, "value": -2.7 },
  { "_id": 3, "value": 0 }
])
```

**Query example**

```
db.numbers.aggregate([
  { $project: {
    "roundedUp": { $ceil: "$value" }
  }}
])
```

**Output**

```
{ "_id": 1, "roundedUp": 4 }
{ "_id": 2, "roundedUp": -2 }
{ "_id": 3, "roundedUp": 0 }
```

## Code examples
<a name="ceil-code"></a>

To view a code example for using the `$ceil` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      "roundedUp": { $ceil: "$value" }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.numbers

    result = list(collection.aggregate([
        { '$project': {
            "roundedUp": { '$ceil': "$value" }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1changeStream
<a name="changeStream"></a>

Not supported by Elastic cluster.

The `$changeStream` aggregation stage opens a change stream cursor to monitor real-time changes to a collection. It returns change event documents when insert, update, replace, or delete operations occur.

**Parameters**
+ `fullDocument`: Specifies whether to return the full document for update operations. Options are `default` or `updateLookup`.
+ `resumeAfter`: Optional. Resume token to continue from a specific point in the change stream.
+ `startAtOperationTime`: Optional. Timestamp to start the change stream from.
+ `allChangesForCluster`: Optional. Boolean value. When `true`, watches all changes across the cluster (for admin database). When `false` (default), watches only the specified collection.

## Example (MongoDB Shell)
<a name="changeStream-examples"></a>

The following example demonstrates using the `$changeStream` stage to monitor changes to a collection.

**Query example**

```
// Open change stream first
const changeStream = db.inventory.aggregate([
  { $changeStream: { fullDocument: "updateLookup" } }
]);

// In another session, insert a document
db.inventory.insertOne({ _id: 1, item: "Widget", qty: 10 });

// Back in the first session, read the change event
if (changeStream.hasNext()) {
  print(tojson(changeStream.next()));
}
```

**Output**

```
{
  _id: { _data: '...' },
  operationType: 'insert',
  clusterTime: Timestamp(1, 1234567890),
  fullDocument: { _id: 1, item: 'Widget', qty: 10 },
  ns: { db: 'test', coll: 'inventory' },
  documentKey: { _id: 1 }
}
```

## Code examples
<a name="changeStream-code"></a>

To view a code example for using the `$changeStream` aggregation stage, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  // Open change stream
  const changeStream = collection.watch([]);

  changeStream.on('change', (change) => {
    console.log('Change detected:', change);
  });

  // Simulate insert in another operation
  setTimeout(async () => {
    await collection.insertOne({ _id: 1, item: 'Widget', qty: 10 });
  }, 1000);

  // Keep connection open to receive changes
  // In production, handle cleanup appropriately
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
import threading
import time

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    # Open change stream
    change_stream = collection.watch([])

    # Insert document in separate thread after delay
    def insert_doc():
        time.sleep(1)
        collection.insert_one({'_id': 1, 'item': 'Widget', 'qty': 10})

    threading.Thread(target=insert_doc).start()

    # Watch for changes
    for change in change_stream:
        print('Change detected:', change)
        break  # Exit after first change

    client.close()

example()
```

------

# \$1cmp
<a name="cmp"></a>

The `$cmp` operator in Amazon DocumentDB is used to compare two values and return an integer value that indicates their relative order. It is a comparison operator that compares two expressions and returns an integer value of -1, 0, or 1, depending on whether the first value is less than, equal to, or greater than the second value, respectively.

**Parameters**
+ `expression1`: The first expression to compare.
+ `expression2`: The second expression to compare.

## Example (MongoDB Shell)
<a name="cmp-examples"></a>

The following example demonstrates the usage of the `$cmp` operator to compare two numeric values.

**Create sample documents**

```
db.collection.insertMany([
  { _id: 1, value1: 10, value2: 20 },
  { _id: 2, value1: 15, value2: 15 },
  { _id: 3, value1: 20, value2: 10 }
]);
```

**Query example**

```
db.collection.find({
  $expr: {
    $cmp: ["$value1", "$value2"]
  }
})
```

**Output**

```
[
  { "_id" : 1, "value1" : 10, "value2" : 20 },
  { "_id" : 3, "value1" : 20, "value2" : 10 }
]
```

In this example, the `$cmp` operator compares the `value1` and `value2` fields for each document. The result is:

```
- `$cmp: ["$value1", "$value2"]` returns -1 for the first document (10 < 20), 0 for the second document (15 = 15), and 1 for the third document (20 > 10).
```

## Code examples
<a name="cmp-code"></a>

To view a code example for using the `$cmp` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of using the `$cmp` operator in a Node.js application with the `mongodb` driver:

```
const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

async function main() {
  await client.connect();
  const db = client.db('test');
  const collection = db.collection('mycollection');

  // Insert sample documents
  await collection.insertMany([
    { _id: 1, value1: 10, value2: 20 },
    { _id: 2, value1: 15, value2: 15 },
    { _id: 3, value1: 20, value2: 10 }
  ]);

  // Query using $cmp operator
  const result = await collection.find({
    $expr: {
      $cmp: ['$value1', '$value2']
    }
  }).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

Here's an example of using the `$cmp` operator in a Python application with the `pymongo` driver:

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['mycollection']

# Insert sample documents
collection.insert_many([
    {'_id': 1, 'value1': 10, 'value2': 20},
    {'_id': 2, 'value1': 15, 'value2': 15},
    {'_id': 3, 'value1': 20, 'value2': 10}
])

# Query using $cmp operator
result = list(collection.find({
    '$expr': {
        '$cmp': ['$value1', '$value2']
    }
}))

print(result)

client.close()
```

The output of both the Node.js and Python examples will be the same as the MongoDB Shell example:

```
[
  { "_id" : 1, "value1" : 10, "value2" : 20 },
  { "_id" : 2, "value1" : 15, "value2" : 15 },
  { "_id" : 3, "value1" : 20, "value2" : 10 }
]
```

------

# \$1collStats
<a name="collStats"></a>

New from version 4.0

The `$collStats` aggregation stage in Amazon DocumentDB provides statistics about the specified collection, similar to the `db.collection.stats()` command in the MongoDB shell. This stage can be used to retrieve information about the collection, such as the number of documents, the total size of the collection, and various performance metrics.

**Parameters**
+ `latencyStats`: (optional) A document that specifies the options for collecting latency statistics. This parameter is not supported in Amazon DocumentDB.
+ `recordStats`: (optional) A document that specifies the options for collecting record statistics. This parameter is not supported in Amazon DocumentDB.
+ `queryExecStats`: (optional) A document that specifies the options for collecting query execution statistics. This parameter is not supported in Amazon DocumentDB.

## Example (MongoDB Shell)
<a name="collStats-examples"></a>

The following example demonstrates how to use the `$collStats` aggregation stage to retrieve statistics about a collection named `test` in the `db` database.

**Create sample documents**

```
db.test.insertMany([
  { "name": "John", "age": 30 },
  { "name": "Jane", "age": 25 },
  { "name": "Bob", "age": 35 }
]);
```

**Query example**

```
db.test.aggregate([
  { $collStats: {} }
]);
```

**Output**

```
{
  "ns" : "db.test",
  "count" : 3,
  "size" : 87,
  "avgObjSize" : 29,
  "storageSize" : 40960,
  "capped" : false,
  "nindexes" : 1,
  "totalIndexSize" : 8192,
  "indexSizes" : {
    "_id_" : 8192
  },
  "collScans" : 0,
  "idxScans" : 0,
  "opCounter" : {
    "numDocsIns" : 3,
    "numDocsUpd" : 0,
    "numDocsDel" : 0
  },
  "cacheStats" : {
    "collBlksHit" : 0,
    "collBlksRead" : 0,
    "collHitRatio" : 0,
    "idxBlksHit" : 0,
    "idxBlksRead" : 0,
    "idxHitRatio" : 0
  },
  "lastReset" : "2023-04-11T12:00:00Z",
  "ok" : 1,
  "operationTime" : Timestamp(1681206000, 1)
}
```

## Code examples
<a name="collStats-code"></a>

To view a code example for using the `$collStats` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of how to use the `$collStats` aggregation stage in a Node.js application using the official MongoDB Node.js driver:

```
const { MongoClient } = require('mongodb');

async function runCollStatsExample() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('db');
  const collection = db.collection('test');

  const result = await collection.aggregate([
    { $collStats: {} }
  ]).toArray();

  console.log(result);

  await client.close();
}

runCollStatsExample();
```

------
#### [ Python ]

Here's an example of how to use the `$collStats` aggregation stage in a Python application using the PyMongo driver:

```
from pymongo import MongoClient

def run_coll_stats_example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['db']
    collection = db['test']

    result = list(collection.aggregate([
        { '$collStats': {} }
    ]))

    print(result)

    client.close()

run_coll_stats_example()
```

------

# \$1concat
<a name="concat"></a>

The `$concat` aggregation operator in Amazon DocumentDB concatenates (or combines) multiple strings in a document to produce a single string that can be returned to the application. This reduces the work done in the application, as the string manipulation is performed at the database level.

**Parameters**
+ `expression1`: The first string to concatenate.
+ `expression2`: The second string to concatenate.
+ `...`: Additional strings to concatenate (optional).

## Example (MongoDB Shell)
<a name="concat-examples"></a>

In this example, we concatenate the first and last names of users to produce each person's full name.

**Create sample documents**

```
db.people.insertMany([
  { "_id":1, "first_name":"Jane", "last_name":"Doe", "DOB":"2/1/1999", "Desk": "MSP102-MN"},
  { "_id":2, "first_name":"John", "last_name":"Doe", "DOB":"12/21/1992", "Desk": "DSM301-IA"},
  { "_id":3, "first_name":"Steve", "last_name":"Smith", "DOB":"3/21/1981", "Desk":"MKE233-WI"}
])
```

**Query example**

```
db.people.aggregate([
  { $project: { full_name: { $concat: [ "$first_name", " ", "$last_name"] } } }
])
```

**Output**

```
{ "_id" : 1, "full_name" : "Jane Doe" }
{ "_id" : 2, "full_name" : "John Doe" }
{ "_id" : 3, "full_name" : "Steve Smith" }
```

## Code examples
<a name="concat-code"></a>

To view a code example for using the `$concat` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function concatenateNames() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');

  const result = await db.collection('people').aggregate([
    { $project: { full_name: { $concat: [ "$first_name", " ", "$last_name"] } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

concatenateNames();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def concatenate_names():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']

    result = list(db.people.aggregate([
        { '$project': { 'full_name': { '$concat': [ '$first_name', ' ', '$last_name' ] } } }
    ]))

    print(result)

    client.close()

concatenate_names()
```

------

# \$1concatArrays
<a name="concatArrays"></a>

The `$concatArrays` aggregation operator in Amazon DocumentDB is used to concatenate two or more arrays into a single array. This can be useful when you need to combine multiple arrays of data into a single array for further processing or analysis.

**Parameters**
+ `array1`: The first array to be concatenated.
+ `array2`: The second array to be concatenated.
+ `[array3, ...]`: (optional) Additional arrays to be concatenated.

## Example (MongoDB Shell)
<a name="concatArrays-examples"></a>

The following example demonstrates how to use the `$concatArrays` operator to combine two arrays into a single array.

**Create sample documents**

```
db.collection.insertMany([
  {
    "_id": 1,
    "name": "John Doe",
    "hobbies": ["reading", "swimming"],
    "skills": ["programming", "design"]
  },
  {
    "_id": 2,
    "name": "Jane Smith",
    "hobbies": ["hiking", "cooking"],
    "skills": ["marketing", "analysis"]
  }
]);
```

**Query example**

```
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      all_activities: { $concatArrays: ["$hobbies", "$skills"] }
    }
  }
]);
```

**Output**

```
[
  {
    "name": "John Doe",
    "all_activities": [
      "reading",
      "swimming",
      "programming",
      "design"
    ]
  },
  {
    "name": "Jane Smith",
    "all_activities": [
      "hiking",
      "cooking",
      "marketing",
      "analysis"
    ]
  }
]
```

## Code examples
<a name="concatArrays-code"></a>

To view a code example for using the `$concatArrays` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('mydb');
  const collection = db.collection('mycollection');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 0,
        name: 1,
        all_activities: { $concatArrays: ['$hobbies', '$skills'] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['mydb']
    collection = db['mycollection']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 0,
                'name': 1,
                'all_activities': { '$concatArrays': ['$hobbies', '$skills'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1cond
<a name="cond"></a>

The `$cond` operator in Amazon DocumentDB is used to evaluate a conditional expression and return one of two possible result expressions.

**Parameters**
+ `if`: The boolean expression to evaluate.
+ `then`: The expression to return if the `if` expression is true.
+ `else`: The expression to return if the `if` expression is false.

## Example (MongoDB Shell)
<a name="cond-examples"></a>

The following example demonstrates the use of the `$cond` operator to return a value based on the age of a person.

**Create sample documents**

```
db.people.insertMany([
  { _id: 1, name: "John Doe", age: 35 },
  { _id: 2, name: "Jane Doe", age: 25 },
  { _id: 3, name: "Bob Smith", age: 65 }
]);
```

**Query example**

```
db.people.aggregate([
  {
    $project: {
      name: 1,
      ageGroup: {
        $cond: {
          if: { $lt: ["$age", 30] },
          then: "young",
          else: {
            $cond: {
              if: { $lt: ["$age", 65] },
              then: "middle-aged",
              else: "elderly"
            }
          }
        }
      }
    }
  }
])
```

**Output**

```
[
  { "_id" : 1, "name" : "John Doe", "ageGroup" : "middle-aged" },
  { "_id" : 2, "name" : "Jane Doe", "ageGroup" : "young" },
  { "_id" : 3, "name" : "Bob Smith", "ageGroup" : "elderly" }
]
```

## Code examples
<a name="cond-code"></a>

To view a code example for using the `$cond` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    { $project: {
        name: 1,
        ageGroup: {
            $cond: {
                if: { $lt: ["$age", 30] },
                then: "young",
                else: {
                    $cond: {
                        if: { $lt: ["$age", 65] },
                        then: "middle-aged",
                        else: "elderly"
                    }
                }
            }
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient


def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'ageGroup': {
                    '$cond': {
                        'if': { '$lt': ["$age", 30]},
                        'then': "young",
                        'else': {
                            '$cond': {
                                'if': { '$lt': ["$age", 65]},
                                'then': "middle-aged",
                                'else': "elderly"
                            }
                        }
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1convert
<a name="convert"></a>

New from version 4.0

The `$convert` operator in Amazon DocumentDB is used to convert a value from one data type to another. This operator is useful when you need to perform operations on data of different types, such as converting a string to a number or a date to a timestamp.

**Parameters**
+ `to`: The target data type to convert the value to. Supported values are `"string"`, `"double"`, `"long"`, `"int"`, `"date"`, and `"boolean"`.
+ `from`: The current data type of the value. If not specified, Amazon DocumentDB will attempt to automatically detect the data type.
+ `onError`: (optional) The value to return if the conversion fails. Can be a specific value or one of the following special values: `"null"`, `"zerofill"`, or `"error"`.
+ `onNull`: (optional) The value to return if the input value is `null`. Can be a specific value or one of the following special values: `"null"`, `"zerofill"`, or `"error"`.

## Example (MongoDB Shell)
<a name="convert-examples"></a>

The following example demonstrates converting a string value to a date using the `$convert` operator.

**Create sample documents**

```
db.users.insertMany([
  { _id: 1, name: "John Doe", joinedOn: "2022-01-01" },
  { _id: 2, name: "Jane Smith", joinedOn: "2023-02-15" },
  { _id: 3, name: "Bob Johnson", joinedOn: "invalid date" }
]);
```

**Query example**

```
db.users.aggregate([
  {
    $project: {
      _id: 1,
      name: 1,
      joinedOn: {
        $convert: {
          input: "$joinedOn",
          to: "date",
          onError: "null",
          onNull: "null"
        }
      }
    }
  }
])
```

**Output**

```
[
  { "_id" : 1, "name" : "John Doe", "joinedOn" : ISODate("2022-01-01T00:00:00Z") },
  { "_id" : 2, "name" : "Jane Smith", "joinedOn" : ISODate("2023-02-15T00:00:00Z") },
  { "_id" : 3, "name" : "Bob Johnson", "joinedOn" : null }
]
```

## Code examples
<a name="convert-code"></a>

To view a code example for using the `$convert` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function example() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const users = db.collection("users");

  const results = await users.aggregate([
    {
      $project: {
        _id: 1,
        name: 1,
        joinedOn: {
          $convert: {
            input: "$joinedOn",
            to: "date",
            onError: "null",
            onNull: "null"
          }
        }
      }
    }
  ]).toArray();

  console.log(results);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    users = db["users"]

    results = list(users.aggregate([
        {
            "$project": {
                "_id": 1,
                "name": 1,
                "joinedOn": {
                    "$convert": {
                        "input": "$joinedOn",
                        "to": "date",
                        "onError": "null",
                        "onNull": "null"
                    }
                }
            }
        }
    ]))

    print(results)
    client.close()

example()
```

------

# \$1count
<a name="count"></a>

The `$count` aggregation stage in Amazon DocumentDB is used to count the number of documents that pass into the stage. It is often used as the final stage in an aggregation pipeline to return the total count of documents matching the previous stages.

**Parameters**
+ `field`: The field to count. This parameter is optional, and if not provided, the stage will count the total number of input documents.

## Example (MongoDB Shell)
<a name="count-examples"></a>

The following example demonstrates how to use the `$count` stage to get the total number of documents in a collection.

**Create sample documents**

```
db.users.insertMany([
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Bob", age: 35 },
  { name: "Alice", age: 28 }
]);
```

**Query example**

```
db.users.aggregate([
  { $count: "total" }
]);
```

**Output**

```
{ "total" : 4 }
```

The example aggregates the `users` collection and uses the `$count` stage to count the total number of documents.

## Code examples
<a name="count-code"></a>

To view a code example for using the `$count` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function countDocuments() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('mydb');
  const collection = db.collection('users');

  const result = await collection.aggregate([
    { $count: "total" }
  ]).toArray();

  console.log(result[0].total);

  await client.close();
}

countDocuments();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def count_documents():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['mydb']
    collection = db['users']

    result = list(collection.aggregate([
        { '$count': "total" }
    ]))

    print(result[0]['total'])

    client.close()

count_documents()
```

------

# \$1currentOp
<a name="currentOp"></a>

The `$currentOp` aggregation stage returns information about currently running operations in the database. This stage is useful for monitoring active queries and operations in an aggregation pipeline.

**Parameters**
+ `allUsers` (optional): When set to `true`, returns operations for all users. Default is `false`.
+ `idleConnections` (optional): When set to `true`, includes idle connections. Default is `false`.
+ `idleCursors` (optional): When set to `true`, includes information about idle cursors. Default is `false`.
+ `idleSessions` (optional): When set to `true`, includes information about idle sessions. Default is `true`.
+ `localOps` (optional): When set to `true`, includes local operations. Default is `false`.

## Example (MongoDB Shell)
<a name="currentOp-examples"></a>

The following example demonstrates using the `$currentOp` aggregation stage to retrieve information about active read operations.

**Query example**

```
db.aggregate([
  { $currentOp: { allUsers: true, idleConnections: false } },
  { $match: { op: "query" } }
])
```

**Output**

```
[
  {
    "opid": "12345",
    "active": true,
    "op": "query",
    "ns": "test.users",
    "secs_running": 2
  }
]
```

## Code examples
<a name="currentOp-code"></a>

To view a code example for using the `$currentOp` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('admin');

  const result = await db.aggregate([
    { $currentOp: { allUsers: true, idleConnections: false } },
    { $match: { op: "query" } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['admin']

    result = list(db.aggregate([
        { '$currentOp': { 'allUsers': True, 'idleConnections': False } },
        { '$match': { 'op': 'query' } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1dateAdd
<a name="dateAdd"></a>

New from version 5.0

The `$dateAdd` aggregation operator in Amazon DocumentDB allows you to add a duration to a date and time value.

**Parameters**
+ `date`: A date and time value to add a duration to.
+ `duration`: The duration to add to the `date` value. This can be specified as an object with keys for `years`, `months`, `weeks`, `days`, `hours`, `minutes`, and `seconds`.
+ `timezone`: (optional) The time zone to use when performing the date addition. If not specified, the default time zone of the Amazon DocumentDB cluster is used.

## Example (MongoDB Shell)
<a name="dateAdd-examples"></a>

The following example demonstrates how to use the `$dateAdd` operator to add 2 days and 12 hours to a date.

**Create sample documents**

```
db.events.insertMany([
  { _id: 1, eventDate: ISODate("2023-04-01T10:00:00Z") },
  { _id: 2, eventDate: ISODate("2023-04-02T12:00:00Z") },
  { _id: 3, eventDate: ISODate("2023-04-03T14:00:00Z") }
]);
```

**Query example**

```
db.events.aggregate([
  {
    $project: {
      _id: 1,
      eventDate: 1,
      eventDatePlustwodaysandtwelvehours: {
        $dateAdd: {
          startDate: {
            $dateAdd: { 
              startDate: "$eventDate",
              unit: "day",
              amount: 2
            }
          },
          unit: "hour",
          amount: 12
        }
      }
    }
  }
])
```

**Output**

```
[
  {
    "_id": 1,
    "eventDate": "2023-04-01T10:00:00Z",
    "eventDatePlustwodaysandtwelvehours": ISODate("2023-04-03T22:00:00Z)"
  },
  {
    "_id": 2,
    "eventDate": "2023-04-02T12:00:00Z",
    "eventDatePlustwodaysandtwelvehours": ISODate("2023-04-05T00:00:00Z)"
  },
  {
    "_id": 3,
    "eventDate": "2023-04-03T14:00:00Z",
    "eventDatePlustwodaysandtwelvehours": ISODate("2023-04-06T02:00:00Z)"
  }
]
```

## Code examples
<a name="dateAdd-code"></a>

To view a code example for using the `$dateAdd` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        eventDate: 1,
        eventDatePlustwodaysandtwelvehours: {
          $dateAdd: {
            startDate: {
              $dateAdd: {
                startDate: "$eventDate",
                unit: "day",
                amount: 2
              }
            },
            unit: "hour",
            amount: 12
          }
        }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from bson.date_time import datetime

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'eventDate': 1,
                'eventDatePlustwodaysandtwelvehours': {
                    '$dateAdd': {
                        'startDate': {
                            '$dateAdd' : {
                                'startDate': '$eventDate',
                                'unit': 'day',
                                'amount': 2,
                            }
                        },
                        'unit': 'hour',
                        'amount': 12,
                    }
                }
            }
        }
    ]))

    print(result)

    client.close()

example()
```

------

# \$1dateDiff
<a name="dateDiff"></a>

New from version 5.0

Not supported by Elastic cluster.

The `$dateDiff` aggregation operator calculates the difference between two dates in specified units. It returns the number of unit boundaries crossed between the start and end dates.

**Parameters**
+ `startDate`: The beginning date expression.
+ `endDate`: The ending date expression.
+ `unit`: The time unit for the difference. Supported units are `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`, and `millisecond`.

## Example (MongoDB Shell)
<a name="dateDiff-examples"></a>

The following example demonstrates how to use the `$dateDiff` operator to calculate the number of days between order placement and delivery.

**Create sample documents**

```
db.shipments.insertMany([
  {
    orderId: 1001,
    orderDate: ISODate("2025-01-10T08:00:00Z"),
    deliveryDate: ISODate("2025-01-15T14:30:00Z")
  },
  {
    orderId: 1002,
    orderDate: ISODate("2025-02-05T10:00:00Z"),
    deliveryDate: ISODate("2025-02-12T16:45:00Z")
  }
]);
```

**Query example**

```
db.shipments.aggregate([
  {
    $project: {
      orderId: 1,
      orderDate: 1,
      deliveryDate: 1,
      daysToDeliver: {
        $dateDiff: {
          startDate: "$orderDate",
          endDate: "$deliveryDate",
          unit: "day"
        }
      }
    }
  }
]);
```

**Output**

```
[
  {
    _id: ObjectId('6924a5f2d66dcae121d29517'),
    orderId: 1001,
    orderDate: ISODate('2025-01-10T08:00:00.000Z'),
    deliveryDate: ISODate('2025-01-15T14:30:00.000Z'),
    daysToDeliver: 5
  },
  {
    _id: ObjectId('6924a5f2d66dcae121d29518'),
    orderId: 1002,
    orderDate: ISODate('2025-02-05T10:00:00.000Z'),
    deliveryDate: ISODate('2025-02-12T16:45:00.000Z'),
    daysToDeliver: 7
  }
]
```

## Code examples
<a name="dateDiff-code"></a>

To view a code example for using the `$dateDiff` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const shipments = db.collection('shipments');
  
  const result = await shipments.aggregate([
    {
      $project: {
        orderId: 1,
        orderDate: 1,
        deliveryDate: 1,
        daysToDeliver: {
          $dateDiff: {
            startDate: "$orderDate",
            endDate: "$deliveryDate",
            unit: "day"
          }
        }
      }
    }
  ]).toArray();
  
  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    shipments = db['shipments']
    
    result = list(shipments.aggregate([
        {
            "$project": {
                "orderId": 1,
                "orderDate": 1,
                "deliveryDate": 1,
                "daysToDeliver": {
                    "$dateDiff": {
                        "startDate": "$orderDate",
                        "endDate": "$deliveryDate",
                        "unit": "day"
                    }
                }
            }
        }
    ]))
    
    print(result)
    client.close()

example()
```

------

# \$1dateFromString
<a name="dateFromString"></a>

The `$dateFromString` aggregation operator in Amazon DocumentDB allows you to convert a date-time string into a date object. This is useful when your data is stored as strings but you need to perform date-based operations on the data.

**Parameters**
+ `dateString`: A string that represents a date and time.
+ `format`: (optional) A string that specifies the format of the `dateString`. If not provided, Amazon DocumentDB will attempt to parse the string in the ISO-8601 format.
+ `timezone`: (optional) A string that specifies the time zone. If not provided, Amazon DocumentDB will use the time zone of the server.
+ `onError`: (optional) Specifies the action to take if the conversion fails. Possible values are `'error'` (the default, which throws an error), `'null'` (returns `null`), or `'replace'` (replaces the value with the replacement string specified in the `onErrorMessage` option).
+ `onErrorMessage`: (optional) If `onError` is set to `'replace'`, this option specifies the replacement string.

## Example (MongoDB Shell)
<a name="dateFromString-examples"></a>

The following example demonstrates how to use `$dateFromString` to convert a date string to a date object in Amazon DocumentDB.

**Create sample documents**

```
db.missionLog.insertMany([
{ _id: 1, event: "missionStart", logDate: "2020-03-15T13:41:33"},
{ _id: 2, event: "jumpPoint1", logDate: "2020-03-15T13:45:34"},
{ _id: 3, event: "jumpPoint2", logDate: "2020-03-15T13:48:21"},
{ _id: 4, event: "jumpPoint3", logDate: "2020-03-15T13:52:09"},
{ _id: 5, event: "missionEnd", logDate: "2020-03-15T13:58:44"}
]);
```

**Query example**

```
db.missionLog.aggregate([
  {
    $project: {
      event: '$event',
      logDate: {
        $dateFromString: {
          dateString: '$logDate'
        }
      }
    }
  }
]);
```

**Output**

```
[
  {
    "_id": 1,
    "event": "missionStart",
    "logDate": ISODate("2020-03-15T13:41:33Z")
  },
  {
    "_id": 2,
    "event": "jumpPoint1",
    "logDate": ISODate("2020-03-15T13:45:34Z")
  },
  {
    "_id": 3,
    "event": "jumpPoint2",
    "logDate": ISODate("2020-03-15T13:48:21Z")
  },
  {
    "_id": 4,
    "event": "jumpPoint3",
    "logDate": ISODate("2020-03-15T13:52:09Z")
  },
  {
    "_id": 5,
    "event": "missionEnd",
    "logDate": ISODate("2020-03-15T13:58:44Z")
  }
]
```

## Code examples
<a name="dateFromString-code"></a>

To view a code example for using the `$dateFromString` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('missionLog');

  const result = await collection.aggregate([
    {
      $project: {
        event: '$event',
        logDate: {
          $dateFromString: {
            dateString: '$logDate'
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['missionLog']

    result = list(collection.aggregate([
        {
            '$project': {
                'event': '$event',
                'logDate': {
                    '$dateFromString': {
                        'dateString': '$logDate'
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1dateSubtract
<a name="dateSubtract"></a>

New from version 5.0

The `$dateSubtract` aggregation operator in Amazon DocumentDB allows you to subtract a specified duration from a date value.

**Parameters**
+ `date`: A date expression that resolves to a date or timestamp.
+ `subtrahend`: A duration expression that specifies the amount of time to subtract from the `date` expression.
+ `unit`: A string that specifies the time unit for the `subtrahend` expression. Supported units are "year", "quarter", "month", "week", "day", "hour", "minute", "second", and "millisecond".

## Example (MongoDB Shell)
<a name="dateSubtract-examples"></a>

The following example demonstrates how to use the `$dateSubtract` operator to calculate the date one year ago from the current date.

**Create sample documents**

```
db.events.insertOne({
  eventName: "Player joined",
  eventTime: ISODate("2023-04-01T12:00:00Z")
});
```

**Query example**

```
db.events.aggregate([
  {
    $project: {
      eventName: 1,
      oneYearAgo: {
        $dateSubtract: {
          startDate: "$eventTime",
          amount: 1,
          unit: "year"
        }
      }
    }
  }
])
```

**Output**

```
{
  "_id" : ObjectId("64567890abcdef012345678"),
  "eventName" : "Player joined",
  "oneYearAgo" : ISODate("2022-04-01T12:00:00Z")
}
```

## Code examples
<a name="dateSubtract-code"></a>

To view a code example for using the `$dateSubtract` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('events');

  const result = await events.aggregate([
    {
      $project: {
        eventName: 1,
        oneYearAgo: {
          $dateSubtract: {
            startDate: "$eventTime",
            amount: 1,
            unit: "year"
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from bson.date_time import datetime

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    events = db['events']

    result = list(events.aggregate([
        {
            '$project': {
                'eventName': 1,
                'oneYearAgo': {
                    '$dateSubtract': {
                        'startDate': '$eventTime',
                        'amount': 1,
                        'unit': 'year'
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1dateToString
<a name="dateToString"></a>

The `$dateToString` aggregation operator in Amazon DocumentDB is used to convert a date or timestamp value to a string representation. This is useful when you need to format the date and time in a specific way for display or further processing.

**Parameters**
+ `date`: The date or timestamp value to be converted to a string.
+ `format`: A string that specifies the format in which the date should be represented. The format string can include various format specifiers, such as `%Y` for the four-digit year, `%m` for the two-digit month, `%d` for the two-digit day of the month, etc.
+ `timezone`: (optional) The time zone to use for the conversion. If not specified, the time zone of the server hosting the Amazon DocumentDB cluster is used.
+ `onNull`: (optional) The value to be returned if the `date` parameter is `null`.

## Example (MongoDB Shell)
<a name="dateToString-examples"></a>

The following example demonstrates the usage of the `$dateToString` operator to format the `logDate` field of the `missionLog` collection.

**Create sample documents**

```
db.missionLog.insertMany([
  { _id: 1, "event":"missionStart", logDate: new Date("2020-03-15T13:41:33Z") },
  { _id: 2, "event":"jumpPoint1", logDate: new Date("2020-03-15T13:45:34Z") },
  { _id: 3, "event":"jumpPoint2", logDate: new Date("2020-03-15T13:48:21Z") },
  { _id: 4, "event":"jumpPoint3", logDate: new Date("2020-03-15T13:52:09Z") },
  { _id: 5, "event":"missionEnd", logDate: new Date("2020-03-15T13:58:44Z") }
]);
```

**Query example**

```
db.missionLog.aggregate([
  {
    $project: {
      event: "$event",
      logDateFormatted: {
        $dateToString: {
          format: "%Y-%m-%d %H:%M:%S",
          date: "$logDate"
        }
      }
    }
  }
])
```

**Output**

```
[
  {
    "_id": 1,
    "event": "missionStart",
    "logDateFormatted": "2020-03-15 13:41:33"
  },
  {
    "_id": 2,
    "event": "jumpPoint1",
    "logDateFormatted": "2020-03-15 13:45:34"
  },
  {
    "_id": 3,
    "event": "jumpPoint2",
    "logDateFormatted": "2020-03-15 13:48:21"
  },
  {
    "_id": 4,
    "event": "jumpPoint3",
    "logDateFormatted": "2020-03-15 13:52:09"
  },
  {
    "_id": 5,
    "event": "missionEnd",
    "logDateFormatted": "2020-03-15 13:58:44"
  }
]
```

## Code examples
<a name="dateToString-code"></a>

To view a code example for using the `$dateToString` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of using the `$dateToString` operator in a Node.js application:

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('missionLog');

  const result = await collection.aggregate([
    {
      $project: {
        event: "$event",
        logDateFormatted: {
          $dateToString: {
            format: "%Y-%m-%d %H:%M:%S",
            date: "$logDate"
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

Here's an example of using the `$dateToString` operator in a Python application:

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['missionLog']

    pipeline = [
        {
            '$project': {
                'event': '$event',
                'logDateFormatted': {
                    '$dateToString': {
                        'format': '%Y-%m-%d %H:%M:%S',
                        'date': '$logDate'
                    }
                }
            }
        }
    ]

    result = list(collection.aggregate(pipeline))
    print(result)
    client.close()

example()
```

------

# \$1dateTrunc
<a name="dateTrunc"></a>

New from version 8.0

Not supported by Elastic cluster.

The `$dateTrunc` aggregation operator in Amazon DocumentDB truncates a date to a specified unit.

**Parameters**
+ `date`: A date expression that resolves to a date or timestamp.
+ `unit`: A string that specifies the time unit for the subtrahend expression. Supported units are `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`, and `millisecond`.

## Example (MongoDB Shell)
<a name="dateTrunc-examples"></a>

The following example demonstrates how to use the `$dateTrunc` operator to truncate a date to to the hour.

**Create sample documents**

```
db.events.insertMany([
  {
    eventName: "Event 1",
    eventTime: ISODate("2025-04-01T12:15:00Z")
  },
  {
    eventName: "Event 2",
    eventTime: ISODate("2025-08-15T14:33:22Z")
  },
]);
```

**Query example**

```
db.events.aggregate([
  {
    $project: {
      eventName: 1,
      eventTime: 1,
      truncatedToHour: {
        $dateTrunc: {
          date: "$eventTime",
          unit: "hour"
        }
      }
    }
  }
]);
```

**Output**

```
[
  {
    _id: ObjectId('6924a258d66dcae121d29515'),
    eventName: 'Event 1',
    eventTime: ISODate('2025-04-01T12:15:00.000Z'),
    truncatedToHour: ISODate('2025-04-01T12:00:00.000Z')
  },
  {
    _id: ObjectId('6924a258d66dcae121d29516'),
    eventName: 'Event 2',
    eventTime: ISODate('2025-08-15T14:33:22.000Z'),
    truncatedToHour: ISODate('2025-08-15T14:00:00.000Z')
  }
]
```

## Code examples
<a name="dateTrunc-code"></a>

To view a code example for using the `$dateTrunc` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('events');
  
  const result = await events.aggregate([
    {
      $project: {
        eventName: 1,
        eventTime: 1,
        truncatedToHour: {
          $dateTrunc: {
            date: "$eventTime",
            unit: "hour"
          }
        }
      }
    }
  ]).toArray();
  
  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    events = db['events']
    
    result = list(events.aggregate([
        {
            "$project": {
                "eventName": 1,
                "eventTime": 1,
                "truncatedToHour": {
                    "$dateTrunc": {
                        "date": "$eventTime",
                        "unit": "hour"
                    }
                }
            }
        }
    ]))
    
    print(result)
    client.close()

example()
```

------

# \$1dayOfMonth
<a name="dayOfMonth"></a>

The `$dayOfMonth` aggregation operator in Amazon DocumentDB retrieves the day of the month (from 1 to 31) for a given date. This operator is useful for grouping, filtering, or extracting the day of the month from date fields in your documents.

**Parameters**
+ `date expression`: The date expression can be a date field from the document, a date object, or a date string.

## Example (MongoDB Shell)
<a name="dayOfMonth-examples"></a>

This example demonstrates how to use the `$dayOfMonth` operator to extract the day of the month from a date field in the document.

**Create sample documents**

```
db.events.insertMany([
  { _id: 1, eventDate: new Date("2022-01-15T12:00:00Z") },
  { _id: 2, eventDate: new Date("2022-02-28T15:30:00Z") },
  { _id: 3, eventDate: new Date("2022-03-01T09:45:00Z") },
  { _id: 4, eventDate: new Date("2022-04-30T23:59:59Z") }
]);
```

**Query example**

```
db.events.aggregate([
  { $project: {
    eventDay: { $dayOfMonth: "$eventDate" }
  }}
])
```

**Output**

```
[
  { "_id" : 1, "eventDay" : 15 },
  { "_id" : 2, "eventDay" : 28 },
  { "_id" : 3, "eventDay" : 1 },
  { "_id" : 4, "eventDay" : 30 }
]
```

## Code examples
<a name="dayOfMonth-code"></a>

To view a code example for using the `$dayOfMonth` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('events');

  const result = await events.aggregate([
    { $project: {
      eventDay: { $dayOfMonth: "$eventDate" }
    }}
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.mydatabase
    events = db.events

    result = list(events.aggregate([
        { "$project": {
            "eventDay": { "$dayOfMonth": "$eventDate" }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1dayOfWeek
<a name="dayOfWeek"></a>

The `$dayOfWeek` operator in Amazon DocumentDB extracts the day of the week from a given date field. It returns the day of the week as a number between 1 (Sunday) and 7 (Saturday), which is the same behavior as in MongoDB.

**Parameters**
+ `date field`: The date field to extract the day of the week from.

## Example (MongoDB Shell)
<a name="dayOfWeek-examples"></a>

This example demonstrates how to use the `$dayOfWeek` operator to extract the day of the week from the `date` field in the `weather` collection.

**Create sample documents**

```
db.weather.insertMany([
  {
    "temperature": 97.5,
    "humidity": 0.60,
    "date": new Date("2023-04-01")
  },
  {
    "temperature": 95.2,
    "humidity": 0.55,
    "date": new Date("2023-04-02")
  },
  {
    "temperature": 92.8,
    "humidity": 0.65,
    "date": new Date("2023-04-03")
  }
]);
```

**Query example**

```
db.weather.aggregate([
  {
    $project: {
      dayOfWeek: { $dayOfWeek: "$date" }
    }
  }
]).pretty();
```

**Output**

```
{ "_id" : ObjectId("64272c6663f4f8ce422c2d91"), "dayOfWeek" : 7 }
{ "_id" : ObjectId("64272c6663f4f8ce422c2d92"), "dayOfWeek" : 1 }
{ "_id" : ObjectId("64272c6663f4f8ce422c2d93"), "dayOfWeek" : 2 }
```

## Code examples
<a name="dayOfWeek-code"></a>

To view a code example for using the `$dayOfWeek` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('weather');

  const result = await collection.aggregate([
    {
      $project: {
        dayOfWeek: { $dayOfWeek: '$date' }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.weather

    result = list(collection.aggregate([
        {
            '$project': {
                'dayOfWeek': { '$dayOfWeek': '$date' }
            }
        }
    ]))

    print(result)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1dayOfYear
<a name="dayOfYear"></a>

The `$dayOfYear` operator in Amazon DocumentDB returns the day of the year for a date as a number between 1 and 366 (365 in non-leap years).

**Parameters**
+ `expression`: The date field or expression from which to extract the day of the year.

## Example (MongoDB Shell)
<a name="dayOfYear-examples"></a>

This example demonstrates how to use the `$dayOfYear` operator to extract the day of the year from a date field in an Amazon DocumentDB collection.

**Create sample documents**

```
db.weather.insert([
  {
    "temperature" : 97.5,
    "humidity": 0.60,
    "date" : new Date("2023-03-15")
  },
  {
    "temperature" : 82.3,
    "humidity": 0.75,
    "date" : new Date("2023-12-31")
  }
])
```

**Query example**

```
db.weather.aggregate([
  {
    $project: {
      dayOfYear: { $dayOfYear: "$date" }
    }
  }
]).pretty()
```

**Output**

```
{ "_id" : ObjectId("642b86fc7d8e07af279bbe63"), "dayOfYear" : 74 }
{ "_id" : ObjectId("642b86fc7d8e07af279bbe64"), "dayOfYear" : 365 }
```

## Code examples
<a name="dayOfYear-code"></a>

To view a code example for using the `$dayOfYear` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('weather');

  const result = await collection.aggregate([
    {
      $project: {
        dayOfYear: { $dayOfYear: "$date" }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['weather']

    result = list(collection.aggregate([
        {
            '$project': {
                'dayOfYear': { '$dayOfYear': '$date' }
            }
        }
    ]))

    print(result)

    client.close()

example()
```

------

# \$1divide
<a name="divide"></a>

The `$divide` operator in the Amazon DocumentDB aggregation pipeline is used to divide one number by another. It is a useful operator for performing mathematical operations on numeric fields within your documents.

**Parameters**
+ `numerator`: The dividend or the number to be divided.
+ `denominator`: The divisor or the number to divide by.

## Example (MongoDB Shell)
<a name="divide-examples"></a>

This example demonstrates how to use the `$divide` operator to calculate the hourly rate for employees based on their yearly salary and the number of working hours per year.

**Create sample documents**

```
db.employees.insertMany([
  { _id: 1, name: "John Doe", salary: 80000, hoursPerYear: 2080 },
  { _id: 2, name: "Jane Smith", salary: 90000, hoursPerYear: 2080 },
  { _id: 3, name: "Bob Johnson", salary: 75000, hoursPerYear: 2080 }
]);
```

**Query example**

```
db.employees.aggregate([
  {
    $project: {
      name: 1,
      hourlyRate: { $divide: ["$salary", "$hoursPerYear"] }
    }
  }
])
```

**Output**

```
[
  { "_id" : 1, "name" : "John Doe", "hourlyRate" : 38.46153846153846 },
  { "_id" : 2, "name" : "Jane Smith", "hourlyRate" : 43.26923076923077 },
  { "_id" : 3, "name" : "Bob Johnson", "hourlyRate" : 36.05769230769231 }
]
```

## Code examples
<a name="divide-code"></a>

To view a code example for using the `$divide` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function calculateHourlyRate() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const employees = db.collection('employees');

  const result = await employees.aggregate([
    {
      $project: {
        name: 1,
        hourlyRate: { $divide: ["$salary", "$hoursPerYear"] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

calculateHourlyRate();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def calculate_hourly_rate():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.mydatabase
    employees = db.employees

    result = list(employees.aggregate([
        {
            '$project': {
                'name': 1,
                'hourlyRate': { '$divide': ['$salary', '$hoursPerYear'] }
            }
        }
    ]))

    print(result)
    client.close()

calculate_hourly_rate()
```

------

# \$1eq
<a name="eq-aggregation"></a>

The `$eq` aggregation operator compares two values and returns `true` if they are equal, otherwise returns `false`.

**Parameters**
+ `expression1`: The first value to compare.
+ `expression2`: The second value to compare.

## Example (MongoDB Shell)
<a name="eq-aggregation-examples"></a>

The following example demonstrates using the `$eq` operator to check if product quantities match target values.

**Create sample documents**

```
db.inventory.insertMany([
  { _id: 1, item: "Widget", qty: 50, target: 50 },
  { _id: 2, item: "Gadget", qty: 30, target: 50 },
  { _id: 3, item: "Tool", qty: 50, target: 40 }
]);
```

**Query example**

```
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      qty: 1,
      target: 1,
      meetsTarget: { $eq: ["$qty", "$target"] }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, item: 'Widget', qty: 50, target: 50, meetsTarget: true },
  { _id: 2, item: 'Gadget', qty: 30, target: 50, meetsTarget: false },
  { _id: 3, item: 'Tool', qty: 50, target: 40, meetsTarget: false }
]
```

## Code examples
<a name="eq-aggregation-code"></a>

To view a code example for using the `$eq` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        qty: 1,
        target: 1,
        meetsTarget: { $eq: ["$qty", "$target"] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'qty': 1,
                'target': 1,
                'meetsTarget': { '$eq': ['$qty', '$target'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1exp
<a name="exp"></a>

New from version 4.0

The `$exp` operator in Amazon DocumentDB allows you to raise the constant e to a given number.

**Parameters**
+ `expression`: The expression to evaluate. This can be any valid aggregation expression, including field references, arithmetic operations, and other aggregation stages.

## Example (MongoDB Shell)
<a name="exp-examples"></a>

The following example demonstrates the use of the `$exp` operator to find all documents where the `quantity` field is greater than the `price` field.

**Create sample documents**

```
db.items.insertMany([
  { item: "canvas", quantity: 4 },
  { item: "journal", quantity: 2 }
]);
```

**Query example**

```
db.items.aggregate([
  { $project: {
    "quantityRaised": {$exp: "$quantity"}}
  }
]);
```

**Output**

```
[
  {
    _id: ObjectId('6920b785311cf98b79d2950d'),
    quantityRaised: 54.598150033144236
  },
  {
    _id: ObjectId('6920b785311cf98b79d2950e'),
    quantityRaised: 7.38905609893065
  }
]
```

## Code examples
<a name="exp-code"></a>

To view a code example for using the `$exp` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function aggregateExp() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const items = db.collection('items');

  const result = await items.aggregate([
    { $project: {
      "quantityRaised": {$exp: "$quantity"}}
    }
    ]).toArray();

  console.log(result);
  client.close();
}

aggregateExp();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def aggregate_exp():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    items = db.items

    result = list(items.aggregate([
      { "$project": {
        "quantityRaised": {"$exp": "$quantity"}}
      }
    ]))

    print(result)
    client.close()

aggregate_exp()
```

------

# \$1filter
<a name="filter"></a>

The `$filter` operator in Amazon DocumentDB is used to apply a filter expression to each element of an array and return an array containing only the elements that match the specified condition. This operator is useful when you need to perform complex filtering operations on array fields within your documents.

**Parameters**
+ `input`: The array field to filter.
+ `as`: The variable name to use for each element of the `input` array within the `cond` expression.
+ `cond`: The boolean expression that determines whether a given element should be included in the output array.

## Example (MongoDB Shell)
<a name="filter-examples"></a>

The following example demonstrates how to use the `$filter` operator to project each order's customer and create a new array field paidItems containing only the items from the items array where the price is greater than 15. Essentially, it filters each order’s items to include only products that cost more than 15.

**Create sample documents**

```
db.orders.insertMany([
  { _id: 1, customer: "abc123", items: [
    { name: "Product A", price: 10, qty: 2 },
    { name: "Product B", price: 20, qty: 1 }
  ]},
  { _id: 2, customer: "def456", items: [
    { name: "Product C", price: 5, qty: 3 },
    { name: "Product D", price: 15, qty: 4 }
  ]},
  { _id: 3, customer: "ghi789", items: [
    { name: "Product E", price: 8, qty: 3 },
    { name: "Product F", price: 12, qty: 1 }
  ]}
]);
```

**Query example**

```
db.orders.aggregate([
  {
    $project: {
      customer: 1,
      paidItems: {
        $filter: {
          input: "$items",
          as: "item",
          cond: { $gt: ["$$item.price", 15] }
        }
      }
    }
  }
]).pretty();
```

**Output**

```
[
  {
    _id: 1,
    customer: 'abc123',
    paidItems: [ { name: 'Product B', price: 20, qty: 1 } ]
  },
  { _id: 2, customer: 'def456', paidItems: [] },
  { _id: 3, customer: 'ghi789', paidItems: [] }
]
```

## Code examples
<a name="filter-code"></a>

To view a code example for using the `$filter` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('orders');

    const result = await collection.aggregate([
      {
        $project: {
          customer: 1,
          paidItems: {
            $filter: {
              input: "$items",
              as: "item",
              cond: { $gt: ["$$item.price", 15] }
            }
          }
        }
      }
    ]).toArray();

    console.log(JSON.stringify(result, null, 2));

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from pprint import pprint

def example():
    uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'
    
    with MongoClient(uri) as client:
        db = client.test
        collection = db.orders

        result = list(collection.aggregate([
            {
                '$project': {
                    'customer': 1,
                    'paidItems': {
                        '$filter': {
                            'input': '$items',
                            'as': 'item',
                            'cond': { '$gt': ['$$item.price', 15] }
                        }
                    }
                }
            }
        ]))

        for doc in result:
            pprint(doc)

example()
```

------

# \$1first
<a name="first"></a>

New from version 5.0.

Not supported by Elastic cluster.

The `$first` operator in Amazon DocumentDB returns the first document from a grouped set of documents. It is commonly used in aggregation pipelines to retrieve the first document that matches a specific condition.

**Parameters**
+ `expression`: The expression to return as the first value in each group.

## Example (MongoDB Shell)
<a name="first-examples"></a>

The following example demonstrates the use of the `$first` operator to retrieve the first item value encountered for each category during the aggregation.

Note: `$first` returns the first document based on the current order of documents in the pipeline. To ensure a specific order (e.g., by date, price, etc.), a `$sort` stage should be used before the `$group` stage.

**Create sample documents**

```
db.products.insertMany([
  { _id: 1, item: "abc", price: 10, category: "food" },
  { _id: 2, item: "jkl", price: 20, category: "food" },
  { _id: 3, item: "xyz", price: 5, category: "toy" },
  { _id: 4, item: "abc", price: 5, category: "toy" }
]);
```

**Query example**

```
db.products.aggregate([
  { $group: { _id: "$category", firstItem: { $first: "$item" } } }
]);
```

**Output**

```
[
  { "_id" : "food", "firstItem" : "abc" },
  { "_id" : "toy", "firstItem" : "xyz" }
]
```

## Code examples
<a name="first-code"></a>

To view a code example for using the `$first` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('products');

    const result = await collection.aggregate([
      { $group: { _id: "$category", firstItem: { $first: "$item" } } }
    ]).toArray();

    console.log(result);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from pprint import pprint

def example():
    client = None
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

        db = client['test']
        collection = db['products']

        result = list(collection.aggregate([
            { '$group': { '_id': '$category', 'firstItem': { '$first': '$item' } } }
        ]))

        pprint(result)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        if client:
            client.close()

example()
```

------

# \$1floor
<a name="floor"></a>

New from version 4.0.

The `$floor` operator in Amazon DocumentDB returns the largest integer that is less than or equal to the specified number. This operator is useful for rounding down numeric values.

**Parameters**
+ `expression`: The numeric expression to round down.

## Example (MongoDB Shell)
<a name="floor-examples"></a>

The following example demonstrates the use of the `$floor` operator to round a decimal value down to the nearest integer.

**Create sample documents**

```
db.numbers.insertOne({ value: 3.14 });
```

**Query example**

```
db.numbers.aggregate([
  { $project: { _id: 0, floored: { $floor: "$value" } } }
]);
```

**Output**

```
{ "floored" : 3 }
```

## Code examples
<a name="floor-code"></a>

To view a code example for using the `$floor` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('numbers');

    const result = await collection.aggregate([
      { $project: { _id: 0, floored: { $floor: "$value" } } }
    ]).toArray();

    console.log(result);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from pprint import pprint

def example():
    client = None
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

        db = client.test
        collection = db.numbers

        result = list(collection.aggregate([
            { '$project': { '_id': 0, 'floored': { '$floor': '$value' }}}
        ]))

        pprint(result)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        if client:
            client.close()

example()
```

------

# \$1geoNear
<a name="geoNear"></a>

The `$geoNear` aggregation stage returns documents in order of proximity to a specified point. It calculates the distance from the point and includes the distance in the output documents.

**Parameters**
+ `near`: The point from which to calculate distances, specified as GeoJSON or legacy coordinates.
+ `distanceField`: The field name to store the calculated distance.
+ `spherical`: Boolean indicating whether to use spherical geometry (required for GeoJSON points).
+ `maxDistance`: Optional. Maximum distance from the center point.
+ `minDistance`: Optional. Minimum distance from the center point.
+ `query`: Optional. Additional filter criteria to apply.
+ `limit`: Optional. Maximum number of documents to return.
+ `key`: Optional. Field to use for geospatial query when multiple geospatial indexes exist.

## Example (MongoDB Shell)
<a name="geoNear-examples"></a>

The following example demonstrates using the `$geoNear` stage to find stores nearest to a given location.

**Create sample documents**

```
db.stores.createIndex({ location: "2dsphere" });

db.stores.insertMany([
  { _id: 1, name: "Store A", location: { type: "Point", coordinates: [-122.4, 37.8] } },
  { _id: 2, name: "Store B", location: { type: "Point", coordinates: [-122.5, 37.7] } },
  { _id: 3, name: "Store C", location: { type: "Point", coordinates: [-122.3, 37.9] } }
]);
```

**Query example**

```
db.stores.aggregate([
  {
    $geoNear: {
      near: { type: "Point", coordinates: [-122.4, 37.8] },
      distanceField: "distance",
      spherical: true
    }
  }
]);
```

**Output**

```
[
  { _id: 1, name: 'Store A', location: { type: 'Point', coordinates: [ -122.4, 37.8 ] }, distance: 0 },
  { _id: 3, name: 'Store C', location: { type: 'Point', coordinates: [ -122.3, 37.9 ] }, distance: 13877.82 },
  { _id: 2, name: 'Store B', location: { type: 'Point', coordinates: [ -122.5, 37.7 ] }, distance: 15557.89 }
]
```

## Code examples
<a name="geoNear-code"></a>

To view a code example for using the `$geoNear` aggregation stage, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('stores');

  const result = await collection.aggregate([
    {
      $geoNear: {
        near: { type: "Point", coordinates: [-122.4, 37.8] },
        distanceField: "distance",
        spherical: true
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['stores']

    result = list(collection.aggregate([
        {
            '$geoNear': {
                'near': { 'type': 'Point', 'coordinates': [-122.4, 37.8] },
                'distanceField': 'distance',
                'spherical': True
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1group
<a name="group"></a>

The `$group` aggregation stage in Amazon DocumentDB allows you to group documents by a specified expression and perform various accumulative operations on the grouped data. This can be useful for tasks such as calculating totals, averages, or other statistics based on the grouped data.

**Parameters**
+ `_id`: Specifies the expression by which the input documents should be grouped. This can be a field name, a computed expression, or a combination of both.
+ `accumulator expressions`: (optional) One or more accumulator expressions that should be applied to the grouped data. These expressions use the accumulator operators mentioned above.

## Example (MongoDB Shell)
<a name="group-examples"></a>

The following example groups customers by their city and calculates the total order amount for each city.

**Create sample documents**

```
db.customers.insertMany([
  { name: "John Doe", city: "New York", orders: [{ amount: 100 }, { amount: 200 }] },
  { name: "Jane Smith", city: "Los Angeles", orders: [{ amount: 150 }, { amount: 300 }] },
  { name: "Bob Johnson", city: "New York", orders: [{ amount: 75 }, { amount: 125 }] },
  { name: "Samantha Lee", city: "Chicago", orders: [{ amount: 50 }, { amount: 100 }] }
]);
```

**Query example**

```
db.customers.aggregate([
  {
    $group: {
      _id: "$city",
      totalOrders: { $sum: { $sum: "$orders.amount" } }
    }
  }
]);
```

**Output**

```
[
  { _id: 'Chicago', totalOrders: 150 },
  { _id: 'Los Angeles', totalOrders: 450 },
  { _id: 'New York', totalOrders: 500 }
]
```

## Code examples
<a name="group-code"></a>

To view a code example for using the `$group` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function groupByCity() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();
    const db = client.db('test');
    const result = await db.collection('customers').aggregate([
      { $unwind: '$orders' },
      {
        $group: {
          _id: '$city',
          totalOrders: { $sum: '$orders.amount' }
        }
      }
    ]).toArray();

    console.log(result);
  } catch (err) {
    console.error('Error during aggregation:', err);
  } finally {
    await client.close();
  }
}

groupByCity();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def group_by_city():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    
    try:
        db = client.test
        result = list(db.customers.aggregate([
            {'$unwind': '$orders'},
            {
                '$group': {
                    '_id': '$city',
                    'totalOrders': {'$sum': '$orders.amount'}
                }
            }
        ]))
        print(result)
    except Exception as e:
        print(f"Error during aggregation: {e}")
    finally:
        client.close()

group_by_city()
```

------

# \$1gt
<a name="gt-aggregation"></a>

The `$gt` aggregation operator compares two values and returns `true` if the first value is greater than the second, otherwise returns `false`.

**Parameters**
+ `expression1`: The first value to compare.
+ `expression2`: The second value to compare.

## Example (MongoDB Shell)
<a name="gt-aggregation-examples"></a>

The following example demonstrates using the `$gt` operator to identify products exceeding a price threshold.

**Create sample documents**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", price: 1200 },
  { _id: 2, name: "Mouse", price: 25 },
  { _id: 3, name: "Monitor", price: 400 }
]);
```

**Query example**

```
db.products.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      expensive: { $gt: ["$price", 100] }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, name: 'Laptop', price: 1200, expensive: true },
  { _id: 2, name: 'Mouse', price: 25, expensive: false },
  { _id: 3, name: 'Monitor', price: 400, expensive: true }
]
```

## Code examples
<a name="gt-aggregation-code"></a>

To view a code example for using the `$gt` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        price: 1,
        expensive: { $gt: ["$price", 100] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'price': 1,
                'expensive': { '$gt': ['$price', 100] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1gte
<a name="gte-aggregation"></a>

The `$gte` aggregation operator compares two values and returns `true` if the first value is greater than or equal to the second, otherwise returns `false`.

**Parameters**
+ `expression1`: The first value to compare.
+ `expression2`: The second value to compare.

## Example (MongoDB Shell)
<a name="gte-aggregation-examples"></a>

The following example demonstrates using the `$gte` operator to check if students passed an exam.

**Create sample documents**

```
db.students.insertMany([
  { _id: 1, name: "Alice", score: 85 },
  { _id: 2, name: "Bob", score: 60 },
  { _id: 3, name: "Charlie", score: 72 }
]);
```

**Query example**

```
db.students.aggregate([
  {
    $project: {
      name: 1,
      score: 1,
      passed: { $gte: ["$score", 70] }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, name: 'Alice', score: 85, passed: true },
  { _id: 2, name: 'Bob', score: 60, passed: false },
  { _id: 3, name: 'Charlie', score: 72, passed: true }
]
```

## Code examples
<a name="gte-aggregation-code"></a>

To view a code example for using the `$gte` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        score: 1,
        passed: { $gte: ["$score", 70] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['students']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'score': 1,
                'passed': { '$gte': ['$score', 70] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1hour
<a name="hour"></a>

The `$hour` operator extracts the hour component from a date or timestamp field.

**Parameters**
+ `dateExpression`: The date to which the operator is applied. This must resolve to a valid BSON date (e.g., a field like \$1createdAt or a date literal).

A parameter can also be specified as a document in the following format:

\$1 date: `&lt;dateExpression&gt;`, timezone: `&lt;timezoneExpression&gt;` \$1

This allows to apply timezone-aware date operations.

```
- `<tzExpression>`: (optional) The timezone of the operation result. It must be a valid expression that resolves to a string formatted as either an Olson Timezone Identifier or a UTC Offset. If no timezone is provided, the result is in UTC.
```

## Example (MongoDB Shell)
<a name="hour-examples"></a>

The following example demonstrates how to use the `$hour` operator to extract the hour component from a date field and group the data accordingly.

**Create sample documents**

```
db.events.insertMany([
  { timestamp: new Date("2023-04-01T10:30:00Z") },
  { timestamp: new Date("2023-04-01T12:45:00Z") },
  { timestamp: new Date("2023-04-02T08:15:00Z") },
  { timestamp: new Date("2023-04-02T16:20:00Z") },
  { timestamp: new Date("2023-04-03T23:59:00Z") }
]);
```

**Query example**

```
db.events.aggregate([
  {
    $project: {
      hour: { $hour: "$timestamp" }
    }
  },
  {
    $group: {
      _id: "$hour",
      count: { $sum: 1 }
    }
  },
  {
    $sort: { _id: 1 }
  }
]);
```

**Output**

```
[
  { "_id": 8, "count": 1 },
  { "_id": 10, "count": 1 },
  { "_id": 12, "count": 1 },
  { "_id": 16, "count": 1 },
  { "_id": 23, "count": 1 }
]
```

This query groups the events by the hour component of the `timestamp` field and counts the number of events for each hour.

## Code examples
<a name="hour-code"></a>

To view a code example for using the `$hour` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  
  try {
    await client.connect();
    const db = client.db('test');
    const collection = db.collection('events');

    const result = await collection.aggregate([
      {
        $project: {
          hour: { $hour: "$timestamp" }
        }
      },
      {
        $group: {
          _id: "$hour",
          count: { $sum: 1 }
        }
      },
      {
        $sort: { _id: 1 }
      }
    ]).toArray();

    console.log(result);
  } catch (error) {
    console.error('Error occurred:', error);
  } finally {
    await client.close();
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from datetime import datetime

def example():
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        
        db = client.test
        collection = db.events

        result = list(collection.aggregate([
            {
                "$project": {
                    "hour": {"$hour": "$timestamp"}
                }
            },
            {
                "$group": {
                    "_id": "$hour",
                    "count": {"$sum": 1}
                }
            },
            {
                "$sort": {"_id": 1}
            }
        ]))

        print(result)

    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        client.close()

example()
```

------

# \$1ifNull
<a name="ifNull"></a>

The `$ifNull` operator is used to return a specified value if the input expression evaluates to null or undefined. This operator can be useful in scenarios where you want to provide a default value or handle null/undefined cases.

**Parameters**
+ `expression`: The expression to evaluate.
+ `replacement`: The value to return if the `<expression>` evaluates to null or undefined.

## Example (MongoDB Shell)
<a name="ifNull-examples"></a>

The following example demonstrates the usage of the `$ifNull` operator to provide a default value when the `name` field is null or undefined.

**Create sample documents**

```
db.users.insertMany([
  { _id: 1, name: "John" },
  { _id: 2, name: null },
  { _id: 3 }
]);
```

**Query example**

```
db.users.aggregate([
  {
    $project: {
      _id: 1,
      name: { $ifNull: ["$name", "No Name"] }
    }
  }
]);
```

**Output**

```
[
  { "_id": 1, "name": "John" },
  { "_id": 2, "name": "No Name" },
  { "_id": 3, "name": "No Name" }
]
```

## Code examples
<a name="ifNull-code"></a>

To view a code example for using the `$ifNull` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  const db = client.db('test');

  const collection = db.collection('users');

  const pipeline = [
    {
      $project: {
        _id: 1,
        name: { $ifNull: ["$name", "No Name"] }
      }
    }
  ];

  const cursor = await collection.aggregate(pipeline);

  await cursor.forEach(doc => {
    console.log(doc);
  });

  await client.close();

}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    
    db = client.test
    collection = db.users

    pipeline = [
        {
            "$project": {
                "_id": 1,
                "name": { "$ifNull": ["$name", "No Name"] }
            }
        }
    ]

    result = collection.aggregate(pipeline)

    for doc in result:
        print(doc)

    client.close()

example()
```

------

# \$1in
<a name="in-aggregation"></a>

The `$in` aggregation operator checks if a specified value exists within an array. It returns `true` if the value is found in the array, and `false` otherwise.

**Parameters**
+ `value`: The value to search for.
+ `array`: The array to search within.

## Example (MongoDB Shell)
<a name="in-aggregation-examples"></a>

The following example demonstrates using the `$in` operator to check if a specific skill exists in each employee's skill set.

**Create sample documents**

```
db.employees.insertMany([
  { _id: 1, name: "Sarah", skills: ["Python", "JavaScript", "SQL"] },
  { _id: 2, name: "Mike", skills: ["Java", "C++", "Go"] },
  { _id: 3, name: "Emma", skills: ["Python", "Ruby", "Rust"] }
]);
```

**Query example**

```
db.employees.aggregate([
  {
    $project: {
      name: 1,
      hasPython: { $in: ["Python", "$skills"] }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, name: 'Sarah', hasPython: true },
  { _id: 2, name: 'Mike', hasPython: false },
  { _id: 3, name: 'Emma', hasPython: true }
]
```

## Code examples
<a name="in-aggregation-code"></a>

To view a code example for using the `$in` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('employees');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        hasPython: { $in: ["Python", "$skills"] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['employees']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'hasPython': { '$in': ['Python', '$skills'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1indexOfArray
<a name="indexOfArray"></a>

The `$indexOfArray` operator in Amazon DocumentDB is used to find the index of the first occurrence of a specified element in an array. This operator returns the zero-based index position of the first element in the array that matches the specified value. If the value is not found, it returns -1.

**Parameters**
+ `array`: The array to search.
+ `value`: The value to search for in the array.
+ `start`: (optional) The position in the array to start the search from. The default value is 0.

## Example (MongoDB Shell)
<a name="indexOfArray-examples"></a>

The following example demonstrates how to use the \$1indexOfArray operator to find the index of the first occurrence of the element "mango" in the "fruits" array for each document.

**Create sample documents**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry", "durian"] },
  { _id: 2, fruits: ["mango", "orange", "pineapple"] },
  { _id: 3, fruits: ["kiwi", "lemon", "mango"] }
]);
```

**Query example**

```
db.collection.aggregate([
  {
    $project: {
      _id: 1,
      fruitIndex: { $indexOfArray: ["$fruits", "mango"] }
    }
  }
]);
```

**Output**

```
{ "_id" : 1, "fruitIndex" : 1 }
{ "_id" : 2, "fruitIndex" : 0 }
{ "_id" : 3, "fruitIndex" : 2 }
```

## Code examples
<a name="indexOfArray-code"></a>

To view a code example for using the `$indexOfArray` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        fruitIndex: { $indexOfArray: ["$fruits", "mango"] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['collection']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'fruitIndex': { '$indexOfArray': ["$fruits", "mango"] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1indexOfBytes
<a name="indexOfBytes"></a>

The \$1indexOfBytes operator in Amazon DocumentDB is used to find the starting index of a substring within a string, based on the byte positions of the characters. This can be useful when working with text data that may contain multi-byte characters, such as those found in non-Latin scripts.

**Parameters**
+ `string`: The input string to search.
+ `substring`: The substring to search for within the input string.
+ `[<start>]`: (optional) The starting position (zero-based) of the search. If not specified, the search starts at the beginning of the string.

## Example (MongoDB Shell)
<a name="indexOfBytes-examples"></a>

The following example demonstrates the use of `$indexOfBytes` to find the index of the first hyphen character in a set of strings representing desk locations.

**Create sample documents**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
```

**Query example**

```
db.people.aggregate([
  { $project: { stateLocation: { $indexOfBytes: ["$Desk", "-"] } } }
]);
```

**Output**

```
{ "_id" : 1, "stateLocation" : 11 }
{ "_id" : 2, "stateLocation" : 6 }
{ "_id" : 3, "stateLocation" : 7 }
{ "_id" : 4, "stateLocation" : 8 }
```

## Code examples
<a name="indexOfBytes-code"></a>

To view a code example for using the `$indexOfBytes` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('people');

  const result = await db.collection('people').aggregate([
    { $project: { stateLocation: { $indexOfBytes: ["$Desk", "-"] } } }
  ]).toArray();
  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']
    
    result = list(db.people.aggregate([
        { '$project': { 'stateLocation': { '$indexOfBytes': ['$Desk', '-'] } } }
    ]))
    print(result)
    client.close()

example()
```

------

# \$1indexOfCP
<a name="indexOfCP"></a>

The `$indexOfCP` operator in Amazon DocumentDB is used to find the index, in code points (CP), of the first occurrence of a specified substring within a string expression. This can be useful when parsing and extracting content from string fields.

**Parameters**
+ `string expression`: The string to search.
+ `substring`: The substring to search for.
+ `[<start>]`: (optional) The position to start the search (zero-based index). Default is 0.

## Example (MongoDB Shell)
<a name="indexOfCP-examples"></a>

In this example, we use the `$indexOfCP` operator to find the index of the first occurrence of the hyphen character - in the Desk field of each document.

**Create sample documents**

```
db.people.insertMany([
  { "_id":1, "name":"John Doe", "Manager":"Jane Doe", "Role":"Developer", "Desk": "Düsseldorf-BVV-021"},
  { "_id":2, "name":"John Stiles", "Manager":"Jane Doe", "Role":"Manager", "Desk": "Munich-HGG-32a"},
  { "_id":3, "name":"Richard Roe", "Manager":"Jorge Souza", "Role":"Product", "Desk": "Cologne-ayu-892.50"},
  { "_id":4, "name":"Mary Major", "Manager":"Jane Doe", "Role":"Solution Architect", "Desk": "Dortmund-Hop-78"}
])
```

**Query example**

```
db.people.aggregate([
  { $project: { stateLocation: { $indexOfCP: [ "$Desk", "-"] } } }
])
```

**Output**

```
{ "_id" : 1, "stateLocation" : 10 }
{ "_id" : 2, "stateLocation" : 6 }
{ "_id" : 3, "stateLocation" : 7 }
{ "_id" : 4, "stateLocation" : 8 }
```

## Code examples
<a name="indexOfCP-code"></a>

To view a code example for using the `$indexOfCP` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    { $project: { stateLocation: { $indexOfCP: [ "$Desk", "-"] } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['people']

result = list(collection.aggregate([
    { '$project': { 'stateLocation': { '$indexOfCP': [ '$Desk', '-' ] } } }
]))

print(result)

client.close()
```

------

# \$1indexStats
<a name="indexStats"></a>

The `$indexStats` aggregation stage in Amazon DocumentDB provides insight into the usage of indexes within a collection. This operator allows you to monitor the access patterns of your indexes, which can help you make informed decisions about index management and optimization.

**Parameters**

None

## Example (MongoDB Shell)
<a name="indexStats-examples"></a>

The following example demonstrates how to use the `$indexStats` operator to analyze the index usage in an Amazon DocumentDB collection.

**Create sample documents**

```
db.grocery.insertMany([
  { _id: 1, product: "milk", quantity: 10 },
  { _id: 2, product: "eggs", quantity: 20 },
  { _id: 3, product: "bread", quantity: 5 },
  { _id: 4, product: "cheese", quantity: 15 },
  { _id: 5, product: "apple", quantity: 8 }
]);
```

**Query example**

```
db.grocery.aggregate([
  { $indexStats: {} }
]);
```

**Output**

```
[
  {
    "name": "_id_",
    "key": {
      "_id": 1
    },
    "host": "docdb-cluster-1.cluster-123456789.us-west-2.docdb.amazonaws.com",
    "accesses": {
      "ops": NumberLong(5),
      "since": ISODate("2023-04-06T12:34:56.789Z")
    }
  },
  {
    "name": "product_1",
    "key": {
      "product": 1
    },
    "host": "docdb-cluster-1.cluster-123456789.us-west-2.docdb.amazonaws.com",
    "accesses": {
      "ops": NumberLong(10),
      "since": ISODate("2023-04-06T12:34:56.789Z")
    }
  }
]
```

In this example, the `$indexStats` operator shows that the `_id_` index has been accessed 5 times, and the `product_1` index has been accessed 10 times since the last reset or server reboot.

## Code examples
<a name="indexStats-code"></a>

To view a code example for using the `$indexStats` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function indexStats() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const result = await db.collection('grocery').aggregate([
    { $indexStats: {} }
  ]).toArray();
  console.log(result);
  await client.close();
}

indexStats();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def index_stats():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    result = list(db.grocery.aggregate([
        { '$indexStats': {} }
    ]))
    print(result)
    client.close()

index_stats()
```

------

# \$1isArray
<a name="isArray"></a>

The `$isArray` operator in Amazon DocumentDB is used to check if a field in a document is an array. This operator can be useful in aggregation pipelines and conditional expressions to handle array-type fields.

**Parameters**
+ `field`: The field path to check if it is an array.

## Example (MongoDB Shell)
<a name="isArray-examples"></a>

This example demonstrates how to use the `$isArray` operator to identify documents where the "inventory" field is an array.

**Create sample documents**

```
db.videos.insertMany([
  { "_id":1, "name":"Live Soft", "inventory": {"Des Moines": 1000, "Ames" : 500}},
  { "_id":2, "name":"Top Pilot", "inventory": {"Mason City": 250, "Des Moines": 1000}},
  { "_id":3, "name":"Romancing the Rock", "inventory": {"Mason City": 250, "Ames" : 500}},
  { "_id":4, "name":"Bravemind", "inventory": [{"location": "Mason City", "count": 250}, {"location": "Des Moines", "count": 1000}, {"location": "Ames", "count": 500}]}
]);
```

**Query example**

```
db.videos.aggregate([
  {
    $match: {
      $isArray: "$inventory"
    }
  },
  {
    $project: {
      _id: 1,
      name: 1,
      "inventory.location": 1,
      "inventory.count": 1
    }
  }
]).pretty();
```

**Output**

```
{
  "_id": 4,
  "name": "Bravemind",
  "inventory": [
    {
      "location": "Mason City",
      "count": 250
    },
    {
      "location": "Des Moines",
      "count": 1000
    },
    {
      "location": "Ames",
      "count": 500
    }
  ]
}
```

## Code examples
<a name="isArray-code"></a>

To view a code example for using the `$isArray` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function run() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('videos');

  const result = await collection.aggregate([
    {
      $match: {
        $isArray: '$inventory'
      }
    },
    {
      $project: {
        _id: 1,
        name: 1,
        "inventory.location": 1,
        "inventory.count": 1
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

run();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['videos']

result = list(collection.aggregate([
    {
        '$match': {
            '$isArray': '$inventory'
        }
    },
    {
        '$project': {
            '_id': 1,
            'name': 1,
            'inventory.location': 1,
            'inventory.count': 1
        }
    }
]))

print(result)

client.close()
```

------

# \$1isoDayOfWeek
<a name="isoDayOfWeek"></a>

The `$isoDayOfWeek` operator in Amazon DocumentDB returns the ISO day of the week for a date as an integer value. The ISO week date system defines each week starting on a Monday and ending on a Sunday, with week 1 being the week that contains the year's first Thursday.

**Parameters**
+ `expression`: The date expression for which to return the ISO day of the week.

## Example (MongoDB Shell)
<a name="isoDayOfWeek-examples"></a>

The following example demonstrates how to use the `$isoDayOfWeek` operator to retrieve the ISO day of the week for a set of event documents.

**Create sample documents**

```
db.events.insertMany([
  { _id: 1, eventDate: ISODate("2023-04-01T12:00:00Z") },
  { _id: 2, eventDate: ISODate("2023-04-02T12:00:00Z") },
  { _id: 3, eventDate: ISODate("2023-04-03T12:00:00Z") },
  { _id: 4, eventDate: ISODate("2023-04-04T12:00:00Z") },
  { _id: 5, eventDate: ISODate("2023-04-05T12:00:00Z") },
  { _id: 6, eventDate: ISODate("2023-04-06T12:00:00Z") },
  { _id: 7, eventDate: ISODate("2023-04-07T12:00:00Z") }
]);
```

**Query example**

```
db.events.aggregate([
  { $project: {
    _id: 1,
    eventDate: 1,
    isoDayOfWeek: { $isoDayOfWeek: "$eventDate" }
  }}
]);
```

**Output**

```
[
  { "_id": 1, "eventDate": ISODate("2023-04-01T12:00:00Z"), "isoDayOfWeek": 6 },
  { "_id": 2, "eventDate": ISODate("2023-04-02T12:00:00Z"), "isoDayOfWeek": 7 },
  { "_id": 3, "eventDate": ISODate("2023-04-03T12:00:00Z"), "isoDayOfWeek": 1 },
  { "_id": 4, "eventDate": ISODate("2023-04-04T12:00:00Z"), "isoDayOfWeek": 2 },
  { "_id": 5, "eventDate": ISODate("2023-04-05T12:00:00Z"), "isoDayOfWeek": 3 },
  { "_id": 6, "eventDate": ISODate("2023-04-06T12:00:00Z"), "isoDayOfWeek": 4 },
  { "_id": 7, "eventDate": ISODate("2023-04-07T12:00:00Z"), "isoDayOfWeek": 5 }
]
```

## Code examples
<a name="isoDayOfWeek-code"></a>

To view a code example for using the `$isoDayOfWeek` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('events');

  const result = await events.aggregate([
    {
      $project: {
        _id: 1,
        eventDate: 1,
        isoDayOfWeek: { $isoDayOfWeek: '$eventDate' }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    events = db.events

    result = list(events.aggregate([
        {
            '$project': {
                '_id': 1,
                'eventDate': 1,
                'isoDayOfWeek': { '$isoDayOfWeek': '$eventDate' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1isoWeek
<a name="isoWeek"></a>

The `$isoWeek` operator in Amazon DocumentDB returns the ISO week number for a date. The ISO week date system is a way of numbering weeks in a year, in which the first week of a new year is the week that contains the first Thursday of that year. This is different from the Gregorian calendar, where the first week of a new year is the week that contains January 1.

**Parameters**

None

## Example (MongoDB Shell)
<a name="isoWeek-examples"></a>

The following example demonstrates how to use the `$isoWeek` operator to retrieve the ISO week number for a given date.

**Create sample documents**

```
db.dates.insertMany([
  { _id: 1, date: new ISODate("2022-01-01") },
  { _id: 2, date: new ISODate("2022-12-31") },
  { _id: 3, date: new ISODate("2023-01-01") }
])
```

**Query example**

```
db.dates.aggregate([
  {
    $project: {
      _id: 1,
      isoWeek: { $isoWeek: "$date" }
    }
  }
])
```

**Output**

```
[
  { "_id": 1, "isoWeek": 52 },
  { "_id": 2, "isoWeek": 52 },
  { "_id": 3, "isoWeek": 1 }
]
```

## Code examples
<a name="isoWeek-code"></a>

To view a code example for using the `$isoWeek` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('dates');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        isoWeek: { $isoWeek: "$date" }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['dates']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'isoWeek': { '$isoWeek': '$date' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1isoWeekYear
<a name="isoWeekYear"></a>

The `$isoWeekYear` operator in Amazon DocumentDB returns the ISO 8601 week year number for a given date. The ISO week year number differs from the Gregorian calendar year in that the week year can be different from the calendar year, especially at the start and end of the year.

**Parameters**
+ `expression`: The date expression for which to return the ISO 8601 week year number.

## Example (MongoDB Shell)
<a name="isoWeekYear-examples"></a>

This example demonstrates how to use the `$isoWeekYear` operator to retrieve the ISO 8601 week year for the date field of each document in the events collection.

**Create sample documents**

```
db.events.insertMany([
  { _id: 1, name: "Event 1", date: ISODate("2022-12-31T00:00:00Z") },
  { _id: 2, name: "Event 2", date: ISODate("2023-01-01T00:00:00Z") },
  { _id: 3, name: "Event 3", date: ISODate("2023-01-02T00:00:00Z") }
]);
```

**Query example**

```
db.events.aggregate([
  { $project: {
    name: 1,
    isoWeekYear: { $isoWeekYear: "$date" }
  }}
]);
```

**Output**

```
[
  { "_id" : 1, "name" : "Event 1", "isoWeekYear" : 2023 },
  { "_id" : 2, "name" : "Event 2", "isoWeekYear" : 2023 },
  { "_id" : 3, "name" : "Event 3", "isoWeekYear" : 2023 }
]
```

## Code examples
<a name="isoWeekYear-code"></a>

To view a code example for using the `$isoWeekYear` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('events');

  const result = await events.aggregate([
    { $project: {
      name: 1,
      isoWeekYear: { $isoWeekYear: '$date' }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    events = db.events

    result = list(events.aggregate([
        { '$project': {
            'name': 1,
            'isoWeekYear': { '$isoWeekYear': '$date' }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1last
<a name="last"></a>

The `$last` operator in Amazon DocumentDB is used to return the last element in an array that matches the query criteria. It is particularly useful for retrieving the most recent or the last element in an array that satisfies a specific condition.

**Parameters**
+ `expression`: The expression to match the array elements.

## Example (MongoDB Shell)
<a name="last-examples"></a>

The following example demonstrates the use of the `$last` operator in combination with `$filter` to retrieve the last element from an array that meets a specific condition (e.g., subject is 'science').

**Create sample documents**

```
db.collection.insertMany([
  {
    "_id": 1,
    "name": "John",
    "scores": [
      { "subject": "math", "score": 82 },
      { "subject": "english", "score": 85 },
      { "subject": "science", "score": 90 }
    ]
  },
  {
    "_id": 2,
    "name": "Jane",
    "scores": [
      { "subject": "math", "score": 92 },
      { "subject": "english", "score": 88 },
      { "subject": "science", "score": 87 }
    ]
  },
  {
    "_id": 3,
    "name": "Bob",
    "scores": [
      { "subject": "math", "score": 75 },
      { "subject": "english", "score": 80 },
      { "subject": "science", "score": 85 }
    ]
  }
]);
```

**Query example**

```
db.collection.aggregate([
    { $match: { name: "John" } },
    {
      $project: {
        name: 1,
        lastScienceScore: {
          $last: {
            $filter: {
              input: "$scores",
              as: "score",
              cond: { $eq: ["$$score.subject", "science"] }
            }
          }
        }
      }
    }
  ]);
```

**Output**

```
[
  {
    _id: 1,
    name: 'John',
    lastScienceScore: { subject: 'science', score: 90 }
  }
]
```

## Code examples
<a name="last-code"></a>

To view a code example for using the `$last` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.aggregate([
    { $match: { name: "John" } },
    {
      $project: {
        name: 1,
        lastScienceScore: {
          $last: {
            $filter: {
              input: "$scores",
              as: "score",
              cond: { $eq: ["$$score.subject", "science"] }
            }
          }
        }
      }
    }
  ]).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():

    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    db = client.test
    collection = db.collection

    pipeline = [
        { "$match": { "name": "John" } },
        {
            "$project": {
                "name": 1,
                "lastScienceScore": {
                    "$last": {
                        "$filter": {
                            "input": "$scores",
                            "as": "score",
                            "cond": { "$eq": ["$$score.subject", "science"] }
                        }
                    }
                }
            }
        }
    ]

    result = list(collection.aggregate(pipeline))

    print(result)

    client.close()

example()
```

------

# \$1let
<a name="let"></a>

The `$let` operator in Amazon DocumentDB is used to bind variables to values and use those variables in the expression. It allows you to define local variables that can be used in subsequent expressions within the same stage of the aggregation pipeline.

**Parameters**
+ `vars`: An object that defines the variables to be used in the expression.
+ `in`: The expression in which the variables defined in the vars parameter are used.

## Example (MongoDB Shell)
<a name="let-examples"></a>

This example demonstrates the usage of the `$let` operator to calculate the area of a rectangle.

**Create sample documents**

```
db.shapes.insertMany([
  { name: "Rectangle 1", length: 5, width: 3 },
  { name: "Rectangle 2", length: 7, width: 4 },
  { name: "Rectangle 3", length: 6, width: 2 }
]);
```

**Query example**

```
db.shapes.aggregate([
  {
    $project: {
      name: 1,
      area: {
        $let: {
          vars: {
            length: "$length",
            width: "$width"
          },
          in: {
            $multiply: ["$$length", "$$width"]
          }
        }
      }
    }
  }
])
```

**Output**

```
[
  {
    "_id": ObjectId("6161e5b1a3eba3c7f2960d03"),
    "name": "Rectangle 1",
    "area": 15
  },
  {
    "_id": ObjectId("6161e5b1a3eba3c7f2960d04"),
    "name": "Rectangle 2",
    "area": 28
  },
  {
    "_id": ObjectId("6161e5b1a3eba3c7f2960d05"),
    "name": "Rectangle 3",
    "area": 12
  }
]
```

## Code examples
<a name="let-code"></a>

To view a code example for using the `$let` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function calculateRectangleAreas() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('shapes');

  const result = await shapes.aggregate([
    {
      $project: {
        name: 1,
        area: {
          $let: {
            vars: {
              length: '$length',
              width: '$width'
            },
            in: {
              $multiply: ['$$length', '$$width']
            }
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

calculateRectangleAreas();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def calculate_rectangle_areas():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.shapes

    result = list(shapes.aggregate([
        {
            '$project': {
                'name': 1,
                'area': {
                    '$let': {
                        'vars': {
                            'length': '$length',
                            'width': '$width'
                        },
                        'in': {
                            '$multiply': ['$$length', '$$width']
                        }
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

calculate_rectangle_areas()
```

------

# \$1limit
<a name="limit"></a>

The `$limit` operator in Amazon DocumentDB is used to restrict the number of documents returned by a query. It is similar to the MongoDB `$limit` operator, but there are some specific considerations when using it with Amazon DocumentDB.

In Amazon DocumentDB, the `$limit` operator is useful for pagination, where you want to retrieve a subset of the total matching documents. It allows you to control the number of documents returned in each response, improving performance and reducing the amount of data transferred over the network.

**Parameters**
+ `limit`: The maximum number of documents to return. This must be a non-negative integer value.

## Example (MongoDB Shell)
<a name="limit-examples"></a>

The following example demonstrates how to use the `$limit` operator to return a maximum of one document that matches the given filter.

**Create sample documents**

```
db.test.insertMany([
  { "_id": 1, "star_rating": 4, "comments": "apple is red" },
  { "_id": 2, "star_rating": 5, "comments": "comfortable couch" },
  { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" },
  { "_id": 4, "star_rating": 5, "comments": "this is a great couch" },
  { "_id": 5, "star_rating": 5, "comments": "interesting couch" }
]);
```

**Query example**

```
db.test.createIndex({ comments: "text" });

db.test.find({
  $and: [
    { star_rating: 5 },
    { $text: { $search: "couch" } }
  ]
}).limit(1);
```

**Output**

```
[ { _id: 2, star_rating: 5, comments: 'comfortable couch' } ]
```

## Code examples
<a name="limit-code"></a>

To view a code example for using the `$limit` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function limitExample() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
      await client.connect();
      
      const db = client.db('test');
      const collection = db.collection('test');

      await collection.createIndex({ comments: 'text' });

      const query = {
        $and: [
          { star_rating: 5 },
          { $text: { $search: "couch" } }
        ]
      };

      const result = await collection.find(query).limit(1).toArray();

      console.log(result);

    } catch (err) {
        console.error("Error:", err);
    } finally {
        await client.close();
    }

}

limitExample();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def limit_example():
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

        db = client['test']
        collection = db['test']

        collection.create_index([('comments', 'text')])

        query = {
            '$and': [
                {'star_rating': 5},
                {'$text': {'$search': 'couch'}}
            ]
        }

        result = collection.find(query).limit(1)

        for doc in result:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        client.close()

limit_example()
```

------

# \$1literal
<a name="literal"></a>

The `$literal` operator in Amazon DocumentDB is used to represent a literal value within an aggregation pipeline stage. It allows you to include a specific value, such as a number, string, or boolean, without interpreting it as a field reference or expression.

This operator is particularly useful when you need to include a literal value as part of a more complex aggregation pipeline, such as when building dynamic query filters or performing calculations.

**Parameters**

None

## Example (MongoDB Shell)
<a name="literal-examples"></a>

The following example demonstrates the use of the `$literal` operator to include a literal value in an aggregation pipeline. The `$literal` operator is used to include the value 18 as a literal value in the \$1gt expression. This allows the aggregation pipeline to compare the age field against the literal value 18 to determine if the person is an adult.

**Create sample documents**

```
db.collection.insertMany([
  { "name": "John Doe", "age": 30, "city": "New York" },
  { "name": "Jane Doe", "age": 25, "city": "Los Angeles" },
  { "name": "Bob Smith", "age": 35, "city": "Chicago" }
]);
```

**Query example**

```
db.collection.aggregate([
  {
    $project: {
      name: 1,
      age: 1,
      city: 1,
      isAdult: { $gt: ["$age", { $literal: 18 }] }
    }
  }
]);
```

**Output**

```
[
  {
    "_id": ObjectId("601234567890abcdef012345"),
    "name": "John Doe",
    "age": 30,
    "city": "New York",
    "isAdult": true
  },
  {
    "_id": ObjectId("601234567890abcdef012346"),
    "name": "Jane Doe",
    "age": 25,
    "city": "Los Angeles",
    "isAdult": true
  },
  {
    "_id": ObjectId("601234567890abcdef012347"),
    "name": "Bob Smith",
    "age": 35,
    "city": "Chicago",
    "isAdult": true
  }
]
```

## Code examples
<a name="literal-code"></a>

To view a code example for using the `$literal` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        age: 1,
        city: 1,
        isAdult: { $gt: ["$age", { $literal: 18 }] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.collection

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'age': 1,
                'city': 1,
                'isAdult': { '$gt': ["$age", { '$literal': 18 }] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1ln
<a name="ln"></a>

New from version 4.0.

The `$ln` operator in Amazon DocumentDB calculates the natural logarithm (base e) of a specified number. It returns the logarithm of the number to the base e.

**Parameters**
+ `expression`: The number for which the natural logarithm will be calculated.

## Example (MongoDB Shell)
<a name="ln-examples"></a>

The following example demonstrates the usage of the `$log` operator to calculate the natural logarithm of a number.

**Create sample documents**

```
db.numbers.insertMany([
  { _id: 1, value: 10 },
  { _id: 2, value: 100 },
  { _id: 3, value: 1000 }
]);
```

**Query example**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    naturalLog: { $ln: "$value" }
  }}
]);
```

**Output**

```
[
  { "_id" : 1, "naturalLog" : 2.302585092994046 },
  { "_id" : 2, "naturalLog" : 4.605170185988092 },
  { "_id" : 3, "naturalLog" : 6.907755278982137 }
]
```

## Code examples
<a name="ln-code"></a>

To view a code example for using the `$ln` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      _id: 1,
      naturalLog: { $ln: "$value" }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
  
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    db = client.test
    collection = db.numbers

    result = list(collection.aggregate([
        { "$project": {
            "_id": 1,
            "naturalLog": { "$ln": "$value" }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1log
<a name="log"></a>

New from version 4.0.

The `$log` operator in Amazon DocumentDB calculates the natural logarithm of a number. It returns the base-e logarithm of the specified number.

**Parameters**
+ `expression`: The number for which the natural logarithm will be calculated.
+ `base`: Base value to calculate log.

## Example (MongoDB Shell)
<a name="log-examples"></a>

The following example demonstrates the usage of the `$log` operator to calculate the natural logarithm of a number.

**Create sample documents**

```
db.numbers.insertMany([
  { _id: 1, value: 10 },
  { _id: 2, value: 100 },
  { _id: 3, value: 1000 }
]);
```

**Query example**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    naturalLog: { $log: ["$value", 10] }
  }}
]);
```

**Output**

```
[
  { "_id" : 1, "naturalLog" : 1 },
  { "_id" : 2, "naturalLog" : 2 },
  { "_id" : 3, "naturalLog" : 2.9999999999999996 }
]
```

## Code examples
<a name="log-code"></a>

To view a code example for using the `$log` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      _id: 1,
      naturalLog: { $log: ["$value", 10] }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    
    db = client.test
    collection = db.numbers

    result = list(collection.aggregate([
        { "$project": {
            "_id": 1,
            "naturalLog": { "$log": ["$value", 10] }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1log10
<a name="log10"></a>

New from version 4.0.

The `$log10` operator in Amazon DocumentDB is used to calculate the base-10 logarithm of a number. It is useful for performing logarithmic calculations on numeric fields within the aggregation pipeline.

**Parameters**
+ `expression`: The numeric expression for which the base-10 logarithm is to be calculated.

## Example (MongoDB Shell)
<a name="log10-examples"></a>

The following example demonstrates how to use the `$log10` operator to calculate the base-10 logarithm of a numeric field.

**Create sample documents**

```
db.numbers.insertMany([
  { _id: 1, value: 1 },
  { _id: 2, value: 10 },
  { _id: 3, value: 100 },
  { _id: 4, value: 1000 }
]);
```

**Query example**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      log10Value: { $log10: "$value" }
    }
  }
]);
```

**Output**

```
[
  { "_id": 1, "log10Value": 0 },
  { "_id": 2, "log10Value": 1 },
  { "_id": 3, "log10Value": 2 },
  { "_id": 4, "log10Value": 3 }
]
```

## Code examples
<a name="log10-code"></a>

To view a code example for using the `$log10` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  let client;

  try {
    client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
    
    const db = client.db('test');
    const collection = db.collection('numbers');

    const result = await collection.aggregate([
      {
        $project: {
          _id: 1,
          log10Value: { $log10: "$value" }
        }
      }
    ]).toArray();

    console.log(result);
  } catch (error) {
    console.error("An error occurred:", error);
  } finally {
    if (client) {
      await client.close();
    }
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = None
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        
        db = client.test
        collection = db.numbers

        result = list(collection.aggregate([
            {
                '$project': {
                    '_id': 1,
                    'log10Value': { '$log10': '$value' }
                }
            }
        ]))

        print(result)
    
    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        if client:
            client.close()

example()
```

------

# \$1lt
<a name="lt-aggregation"></a>

The `$lt` aggregation operator compares two values and returns `true` if the first value is less than the second, otherwise returns `false`.

**Parameters**
+ `expression1`: The first value to compare.
+ `expression2`: The second value to compare.

## Example (MongoDB Shell)
<a name="lt-aggregation-examples"></a>

The following example demonstrates using the `$lt` operator to identify low stock items.

**Create sample documents**

```
db.warehouse.insertMany([
  { _id: 1, item: "Bolts", stock: 5 },
  { _id: 2, item: "Nuts", stock: 25 },
  { _id: 3, item: "Screws", stock: 8 }
]);
```

**Query example**

```
db.warehouse.aggregate([
  {
    $project: {
      item: 1,
      stock: 1,
      lowStock: { $lt: ["$stock", 10] }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, item: 'Bolts', stock: 5, lowStock: true },
  { _id: 2, item: 'Nuts', stock: 25, lowStock: false },
  { _id: 3, item: 'Screws', stock: 8, lowStock: true }
]
```

## Code examples
<a name="lt-aggregation-code"></a>

To view a code example for using the `$lt` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('warehouse');

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        stock: 1,
        lowStock: { $lt: ["$stock", 10] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['warehouse']

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'stock': 1,
                'lowStock': { '$lt': ['$stock', 10] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1lte
<a name="lte-aggregation"></a>

The `$lte` aggregation operator compares two values and returns `true` if the first value is less than or equal to the second, otherwise returns `false`.

**Parameters**
+ `expression1`: The first value to compare.
+ `expression2`: The second value to compare.

## Example (MongoDB Shell)
<a name="lte-aggregation-examples"></a>

The following example demonstrates using the `$lte` operator to identify budget-friendly items.

**Create sample documents**

```
db.menu.insertMany([
  { _id: 1, dish: "Salad", price: 8 },
  { _id: 2, dish: "Pasta", price: 12 },
  { _id: 3, dish: "Soup", price: 6 }
]);
```

**Query example**

```
db.menu.aggregate([
  {
    $project: {
      dish: 1,
      price: 1,
      affordable: { $lte: ["$price", 10] }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, dish: 'Salad', price: 8, affordable: true },
  { _id: 2, dish: 'Pasta', price: 12, affordable: false },
  { _id: 3, dish: 'Soup', price: 6, affordable: true }
]
```

## Code examples
<a name="lte-aggregation-code"></a>

To view a code example for using the `$lte` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('menu');

  const result = await collection.aggregate([
    {
      $project: {
        dish: 1,
        price: 1,
        affordable: { $lte: ["$price", 10] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['menu']

    result = list(collection.aggregate([
        {
            '$project': {
                'dish': 1,
                'price': 1,
                'affordable': { '$lte': ['$price', 10] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1lookup
<a name="lookup"></a>

The `$lookup` aggregation stage in Amazon DocumentDB allows you to perform a left outer join between two collections. This operation lets you combine data from multiple collections based on matching field values. It is particularly useful when you need to incorporate data from related collections into your query results.

**Parameters**
+ `from`: The name of the collection to perform the join with.
+ `localField`: The field from the input documents to match against the `foreignField`.
+ `foreignField`: The field from the documents in the `from` collection to match against the `localField`.
+ `as`: The name of the new field to add to the output documents containing the matching documents from the `from` collection.

## Example (MongoDB Shell)
<a name="lookup-examples"></a>

The following example demonstrates a simple `$lookup` operation that joins data from the `orders` collection into the `customers` collection.

**Create sample documents**

```
db.customers.insertMany([
  { _id: 1, name: "Alice" },
  { _id: 2, name: "Bob" },
  { _id: 3, name: "Charlie" }
]);

db.orders.insertMany([
  { _id: 1, customer_id: 1, total: 50 },
  { _id: 2, customer_id: 1, total: 100 },
  { _id: 3, customer_id: 2, total: 75 }
]);
```

**Query example**

```
db.customers.aggregate([
  {
    $lookup: {
      from: "orders",           
      localField: "_id",        
      foreignField: "customer_id", 
      as: "orders" 
    }
  }
]);
```

**Output**

```
[
  {
    _id: 1,
    name: 'Alice',
    orders: [
      { _id: 2, customer_id: 1, total: 100 },
      { _id: 1, customer_id: 1, total: 50 }
    ]
  },
  { _id: 3, name: 'Charlie', orders: [] },
  {
    _id: 2,
    name: 'Bob',
    orders: [ { _id: 3, customer_id: 2, total: 75 } ]
  }
]
```

## Code examples
<a name="lookup-code"></a>

To view a code example for using the `$lookup` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  await client.connect();

  const db = client.db('test');

  const result = await db.collection('customers').aggregate([
    {
      $lookup: {
        from: 'orders',
        localField: '_id',
        foreignField: 'customer_id',
        as: 'orders'
      }
    }
  ]).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    db = client.test
    
    collection = db.customers

    pipeline = [
        {
            "$lookup": {
                "from": "orders",
                "localField": "_id",
                "foreignField": "customer_id",
                "as": "orders"
            }
        }
    ]

    result = collection.aggregate(pipeline)

    for doc in result:
        print(doc)

    client.close()

example()
```

------

# \$1ltrim
<a name="ltrim"></a>

New from version 4.0.

Not supported by Elastic cluster.

The `$ltrim` operator in Amazon DocumentDB is used to remove leading characters from a string. By default, it removes leading whitespace characters, but you can also specify a set of characters to remove by passing the chars argument.

**Parameters**
+ `input`: The input string from which to remove leading whitespace characters.
+ `chars`: (optional) To remove specific characters.

## Example (MongoDB Shell)
<a name="ltrim-examples"></a>

The following example demonstrates the usage of `$ltrim` to remove specified characters (" \$1") from the beginning of a string.

**Create sample documents**

```
db.collection.insertMany([
  { name: " *John Doe", age: 30 },
  { name: "Jane Doe*", age: 25 },
  { name: "  Bob Smith  ", age: 35 }
]);
```

**Query example**

```
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      name: {
        $ltrim: { input: "$name", chars: " *" }  
      },
      age: 1
    }
  }
]);
```

**Output**

```
[
  { "name": "John Doe", "age": 30 },
  { "name": "Jane Doe ", "age": 25 },
  { "name": "Bob Smith  ", "age": 35 }
]
```

## Code examples
<a name="ltrim-code"></a>

To view a code example for using the `$ltrim` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('collection');

    const pipeline = [
      {
        $project: {
          _id: 0,
          name: {
            $ltrim: {
              input: '$name',
              chars: ' *'
            }
          },
          age: 1
        }
      }
    ];

    const result = await collection.aggregate(pipeline).toArray();

    console.dir(result, { depth: null });

  } finally {
    await client.close();
  }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

        db = client.test
        collection = db.collection

        pipeline = [
            {
                "$project": {
                    "_id": 0,
                    "name": {
                        "$ltrim": {
                            "input": "$name",
                            "chars": " *"
                        }
                    },
                    "age": 1
                }
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        client.close()

example()
```

------

# \$1map
<a name="map"></a>

The `$map` operator in Amazon DocumentDB allows you to apply a specified expression to each element in an array and return a new array with the transformed elements. This operator is particularly useful for manipulating and transforming data within arrays, which can help simplify your application code and improve query performance by pushing the array processing to the database level.

**Parameters**
+ `input`: The array to be transformed.
+ `as`: (optional) The name of the variable to be used within the in expression to represent the current element being processed.
+ `in`: The expression to be applied to each element in the input array.

## Example (MongoDB Shell)
<a name="map-examples"></a>

The following example demonstrates how to use the \$1map operator to transform an array of numbers, doubling each value.

**Create sample documents**

```
db.collection.insertMany([
  { _id: 1, numbers: [1, 2, 3, 4, 5] },
  { _id: 2, numbers: [10, 20, 30, 40, 50] }
])
```

**Query example**

```
db.collection.aggregate([
  {
    $project: {
      doubledNumbers: { $map: { input: "$numbers", as: "num", in: { $multiply: ["$$num", 2] } } }
    }
  }
])
```

**Output**

```
[
  { _id: 1, doubledNumbers: [2, 4, 6, 8, 10] },
  { _id: 2, doubledNumbers: [20, 40, 60, 80, 100] }
]
```

## Code examples
<a name="map-code"></a>

To view a code example for using the `$map` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.aggregate([
    {
      $project: {
        doubledNumbers: { $map: { input: "$numbers", as: "num", in: { $multiply: ["$$num", 2] } } }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.collection

    result = list(collection.aggregate([
        {
            '$project': {
                'doubledNumbers': { '$map': { 'input': '$numbers', 'as': 'num', 'in': { '$multiply': ['$$num', 2] } } }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1match
<a name="match"></a>

The `$match` pipeline stage in Amazon DocumentDB is used to filter the input documents to only those that match the specified query criteria. It is one of the most commonly used pipeline stages in aggregation operations. The `$match` stage is applied before any other pipeline stages, allowing you to efficiently reduce the number of documents that need to be processed by the subsequent stages.

**Parameters**
+ `query`: A document that expresses the selection criteria for the operation. The query document uses the same syntax as the `find()` method.

## Example (MongoDB Shell)
<a name="match-examples"></a>

The following example demonstrates the use of the `$match` stage to filter documents based on a specific field value.

**Create sample documents**

```
db.collection.insertMany([
  { _id: 1, name: "John", age: 25, city: "New York" },
  { _id: 2, name: "Jane", age: 30, city: "Los Angeles" },
  { _id: 3, name: "Bob", age: 35, city: "Chicago" },
  { _id: 4, name: "Alice", age: 40, city: "Miami" }
]);
```

**Query example**

```
db.collection.aggregate([
  { $match: { age: { $gt: 30 } } },
  { $project: { _id: 1, name: 1, city: 1 } }
]);
```

**Output**

```
[
  { "_id": 3, "name": "Bob", "city": "Chicago" },
  { "_id": 4, "name": "Alice", "city": "Miami" }
]
```

The `$match` stage filters the documents to include only those where the `age` field is greater than 30.

## Code examples
<a name="match-code"></a>

To view a code example for using the `$match` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.aggregate([
    { $match: { age: { $gt: 30 } } },
    { $project: { _id: 1, name: 1, city: 1 } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    
    db = client['test']
    collection = db['collection']

    result = list(collection.aggregate([
        { '$match': { 'age': { '$gt': 30 } } },
        { '$project': { '_id': 1, 'name': 1, 'city': 1 } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1max
<a name="max"></a>

The `$max` aggregation stage is used to return the maximum value of a specified field across all documents in a pipeline stage. This operator is useful for finding the highest value in a set of documents.

**Parameters**
+ `expression`: The expression to use to calculate the maximum value.

## Example (MongoDB Shell)
<a name="max-examples"></a>

The following example demonstrates how to use the `$max` operator to find the maximum score in a collection of student documents. The `$group` stage groups all documents together, and the `$max` operator is used to calculate the maximum value of the `score` field across all documents.

**Create sample documents**

```
db.students.insertMany([
  { name: "John", score: 85 },
  { name: "Jane", score: 92 },
  { name: "Bob", score: 78 },
  { name: "Alice", score: 90 }
])
```

**Query example**

```
db.students.aggregate([
  { $group: { _id: null, maxScore: { $max: "$score" } } },
  { $project: { _id: 0, maxScore: 1 } }
])
```

**Output**

```
[ { maxScore: 92 } ]
```

## Code examples
<a name="max-code"></a>

To view a code example for using the `$max` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findMaxScore() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const students = db.collection('students');

  const result = await students.aggregate([
    { $group: { _id: null, maxScore: { $max: "$score" } } }
  ]).toArray();

  console.log(result);
  await client.close();
}

findMaxScore();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_max_score():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    students = db.students

    result = list(students.aggregate([
        { "$group": { "_id": None, "maxScore": { "$max": "$score" } } }
    ]))

    print(result)
    client.close()

find_max_score()
```

------

# \$1meta
<a name="meta-aggregation"></a>

The `$meta` aggregation operator accesses metadata associated with documents in an aggregation pipeline. It is commonly used to retrieve text search scores and sort results by relevance.

**Parameters**
+ `textScore`: Retrieves the text search score indicating document relevance to the search query.

## Example (MongoDB Shell)
<a name="meta-aggregation-examples"></a>

The following example demonstrates using the `$meta` operator in an aggregation pipeline to retrieve and sort by text search scores.

**Create sample documents**

```
db.articles.createIndex({ content: "text" });

db.articles.insertMany([
  { _id: 1, title: "Python Programming", content: "Python is a versatile programming language used for web development." },
  { _id: 2, title: "Python Guide", content: "Learn Python programming with Python tutorials and Python examples." },
  { _id: 3, title: "Java Basics", content: "Java is another popular programming language." }
]);
```

**Query example**

```
db.articles.aggregate([
  { $match: { $text: { $search: "Python" } } },
  { $addFields: { score: { $meta: "textScore" } } },
  { $sort: { score: -1 } }
]);
```

**Output**

```
[
  {
    _id: 2,
    title: 'Python Guide',
    content: 'Learn Python programming with Python tutorials and Python examples.',
    score: 1.5
  },
  {
    _id: 1,
    title: 'Python Programming',
    content: 'Python is a versatile programming language used for web development.',
    score: 0.75
  }
]
```

## Code examples
<a name="meta-aggregation-code"></a>

To view a code example for using the `$meta` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('articles');

  const result = await collection.aggregate([
    { $match: { $text: { $search: "Python" } } },
    { $addFields: { score: { $meta: "textScore" } } },
    { $sort: { score: -1 } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['articles']

    result = list(collection.aggregate([
        { '$match': { '$text': { '$search': 'Python' } } },
        { '$addFields': { 'score': { '$meta': 'textScore' } } },
        { '$sort': { 'score': -1 } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1merge
<a name="merge"></a>

Introduced in 8.0

The `$merge` aggregation stage in Amazon DocumentDB is used to merge the results of the previous pipeline stage into a target collection. This is useful for updating or inserting documents in a target collection based on the data from the input documents.

The `$merge` stage allows you to perform various actions based on the matching condition between the input documents and the target collection, such as:

```
- Insert new documents
- Update existing documents
- Delete documents
- Fail the operation if there are any conflicts
```

**Parameters**
+ `into`: (required) The name of the target collection to merge the input documents into.
+ `on`: (required) The field(s) to use as the matching condition between the input documents and the target collection.
+ `whenMatched`: (optional) The action to perform when the input document matches an existing document in the target collection. Supported values are: `"merge"`, `"replace"`, `"keepExisting"`, and `"fail"`.
+ `whenNotMatched`: (optional) The action to perform when the input document does not match any document in the target collection. Supported values are: `"insert"` and `"fail"`.

## Example (MongoDB Shell)
<a name="merge-examples"></a>

The following example demonstrates how to use the `$merge` stage to update a `users` collection with new data from an input pipeline.

**Create sample documents**

```
db.users.insertMany([
  { _id: 1, name: "John Doe", email: "john@example.com" },
  { _id: 2, name: "Jane Smith", email: "jane@example.com" }
]);

db.inputData.insertMany([
  { _id: 1, name: "John Doe", email: "john@example.com", phone: "123-456-7890" },
  { _id: 3, name: "Bob Johnson", email: "bob@example.com", phone: "987-654-3210" }
]);
```

**Query example**

```
db.inputData.aggregate([
  {
    $merge: {
      into: "users",
      on: "_id",
      whenMatched: "merge",
      whenNotMatched: "insert"
    }
  }
])
```

**Output**

After running the `$merge` pipeline, the `users` collection will contain the following documents:

```
[
  { _id: 1, name: "John Doe", email: "john@example.com", phone: "123-456-7890" },
  { _id: 2, name: "Jane Smith", email: "jane@example.com" },
  { _id: 3, name: "Bob Johnson", email: "bob@example.com", phone: "987-654-3210" }
]
```

## Code examples
<a name="merge-code"></a>

To view a code example for using the `$merge` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of using the \$1merge operator in a Node.js application:

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');

  await db.collection('inputData').aggregate([
    {
      $merge: {
        into: 'users',
        on: '_id',
        whenMatched: 'merge',
        whenNotMatched: 'insert'
      }
    }
  ]).toArray();

  const users = await db.collection('users').find({}).toArray();
  console.log(users);

  await client.close();
}

example();
```

------
#### [ Python ]

Here's an example of using the \$1merge operator in a Python application:

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']

    # Assumes collections 'users' and 'inputData' already exist with sample data
    db.inputData.aggregate([
        {
            '$merge': {
                'into': 'users',
                'on': '_id',
                'whenMatched': 'merge',
                'whenNotMatched': 'insert'
            }
        }
    ])

    users = list(db.users.find({}))
    print(users)

    client.close()

example()
```

------

# \$1mergeObjects
<a name="mergeObjects"></a>

The `$mergeObjects` operator in Amazon DocumentDB is used to combine multiple documents or objects into a single document. This operator is particularly useful when you need to merge the contents of two or more documents or objects, potentially overwriting values from one object with those from another.

**Parameters**
+ `expression1`: The first object to be merged.
+ `expression2`: (optional) The second object to be merged.
+ `expression3`: (optional) Additional objects to be merged.

## Example (MongoDB Shell)
<a name="mergeObjects-examples"></a>

The following example demonstrates how to use the `$mergeObjects` operator to combine two objects.

**Create sample documents**

```
db.collection.insertMany([
  { "_id": 1, "name": "John", "address": { "city": "New York", "state": "NY" } },
  { "_id": 2, "name": "Jane", "address": { "city": "Los Angeles", "state": "CA" } }
]);
```

**Query example**

```
db.collection.aggregate([
  {
    $project: {
      "combinedAddress": {
        $mergeObjects: ["$address", { "country": "USA" }]
      }
    }
  }
])
```

**Output**

```
[
  {
    "_id": 1,
    "combinedAddress": {
      "city": "New York",
      "state": "NY",
      "country": "USA"
    }
  },
  {
    "_id": 2,
    "combinedAddress": {
      "city": "Los Angeles",
      "state": "CA",
      "country": "USA"
    }
  }
]
```

## Code examples
<a name="mergeObjects-code"></a>

To view a code example for using the `$mergeObjects` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.aggregate([
    {
      $project: {
        "combinedAddress": {
          $mergeObjects: ["$address", { "country": "USA" }]
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['collection']

    result = list(collection.aggregate([
        {
            '$project': {
                "combinedAddress": {
                    "$mergeObjects": ["$address", { "country": "USA" }]
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1millisecond
<a name="millisecond"></a>

The `$millisecond` operator in Amazon DocumentDB is used to extract the millisecond portion of a date value.

**Parameters**

None

## Example (MongoDB Shell)
<a name="millisecond-examples"></a>

This example demonstrates how to use the `$millisecond` operator to extract the millisecond portion of a date value.

**Create sample documents**

```
db.events.insert([
  {
    "name": "Event 1",
    "timestamp": ISODate("2023-04-21T10:30:15.123Z")
  },
  {
    "name": "Event 2",
    "timestamp": ISODate("2023-04-21T10:30:15.456Z")
  },
  {
    "name": "Event 3",
    "timestamp": ISODate("2023-04-21T10:30:15.789Z")
  }
])
```

**Query example**

```
db.events.aggregate([
  {
    $project: {
      name: 1,
      milliseconds: { $millisecond: "$timestamp" }
    }
  }
])
```

**Output**

```
[
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c1"),
    "name": "Event 1",
    "milliseconds": 123
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c2"),
    "name": "Event 2",
    "milliseconds": 456
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c3"),
    "name": "Event 3",
    "milliseconds": 789
  }
]
```

## Code examples
<a name="millisecond-code"></a>

To view a code example for using the `$millisecond` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('events');

  const result = await events.aggregate([
    {
      $project: {
        name: 1,
        milliseconds: { $millisecond: '$timestamp' }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
events = db['events']

result = list(events.aggregate([
    {
        '$project': {
            'name': 1,
            'milliseconds': { '$millisecond': '$timestamp' }
        }
    }
]))

print(result)

client.close()
```

------

# \$1min
<a name="min"></a>

The `$min` operator returns the minimum value from an array of values. It can be used in aggregation stages to find the minimum value for a specified field across multiple documents.

**Parameters**
+ `expression`: The expression to evaluate. This can be a field path, a variable, or any expression that resolves to a value.

## Example (MongoDB Shell)
<a name="min-examples"></a>

The following example demonstrates the usage of the `$min` operator to find the minimum value of the `age` field across multiple documents.

**Create sample documents**

```
db.users.insertMany([
  { name: "John", age: 35 },
  { name: "Jane", age: 28 },
  { name: "Bob", age: 42 },
  { name: "Alice", age: 31 }
]);
```

**Query example**

```
db.users.aggregate([
  { $group: { _id: null, minAge: { $min: "$age" } } },
  { $project: { _id: 0, minAge: 1 } }
])
```

**Output**

```
[ { minAge: 28 } ]
```

## Code examples
<a name="min-code"></a>

To view a code example for using the `$min` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findMinAge() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([
    { $group: {
        _id: null,
        minAge: { $min: "$age" }
      }}
  ]).toArray();

  console.log(result);
  client.close();
}

findMinAge();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_min_age():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db.users

    result = list(users.aggregate([
        { "$group": {
            "_id": None,
            "minAge": { "$min": "$age" }
        }}
    ]))

    print(result)
    client.close()

find_min_age()
```

------

# \$1minute
<a name="minute"></a>

The `$minute` aggregation pipeline stage in Amazon DocumentDB extracts the minute value from a date or timestamp field.

This operator is useful when you need to perform date and time-based calculations or grouping within your aggregation pipeline.

**Parameters**
+ `expression`: The date or timestamp field from which to extract the minute value.

## Example (MongoDB Shell)
<a name="minute-examples"></a>

The following example demonstrates how to use the `$minute` operator to group the documents by the minute value extracted from the timestamp field and count the number of documents in each group.

**Create sample documents**

```
db.events.insertMany([
  { timestamp: new Date("2023-04-15T10:30:25.000Z") },
  { timestamp: new Date("2023-04-15T10:30:35.000Z") },
  { timestamp: new Date("2023-04-15T10:31:05.000Z") },
  { timestamp: new Date("2023-04-15T10:31:45.000Z") },
  { timestamp: new Date("2023-04-15T10:32:15.000Z") }
]);
```

**Query example**

```
db.events.aggregate([
  {
    $group: {
      _id: {
        minute: { $minute: "$timestamp" }
      },
      count: { $count: {} }
    }
  },
  { $sort: { "_id.minute": 1 } }
]);
```

**Output**

```
[
  { "_id": { "minute": 30 }, "count": 2 },
  { "_id": { "minute": 31 }, "count": 2 },
  { "_id": { "minute": 32 }, "count": 1 }
]
```

## Code examples
<a name="minute-code"></a>

To view a code example for using the `$minute` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  await collection.insertMany([
    { timestamp: new Date("2023-04-15T10:30:25.000Z") },
    { timestamp: new Date("2023-04-15T10:30:35.000Z") },
    { timestamp: new Date("2023-04-15T10:31:05.000Z") },
    { timestamp: new Date("2023-04-15T10:31:45.000Z") },
    { timestamp: new Date("2023-04-15T10:32:15.000Z") }
  ]);

  const result = await collection.aggregate([
    {
      $group: {
        _id: {
          minute: { $minute: "$timestamp" }
        },
        count: { $count: {} }
      }
    },
    { $sort: { "_id.minute": 1 } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from datetime import datetime

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    collection.insert_many([
        {'timestamp': datetime(2023, 4, 15, 10, 30, 25)},
        {'timestamp': datetime(2023, 4, 15, 10, 30, 35)},
        {'timestamp': datetime(2023, 4, 15, 10, 31, 5)},
        {'timestamp': datetime(2023, 4, 15, 10, 31, 45)},
        {'timestamp': datetime(2023, 4, 15, 10, 32, 15)}
    ])

    result = list(collection.aggregate([
        {
            '$group': {
                '_id': {
                    'minute': {'$minute': '$timestamp'}
                },
                'count': {'$count': {}}
            }
        },
        {'$sort': {'_id.minute': 1}}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1mod
<a name="mod"></a>

The `$mod` operator is an arithmetic operator that performs a modulo operation on a number. It returns the remainder of dividing one number by another. This operator is commonly used to determine if a number is odd or even, or to distribute items into a finite number of groups.

**Parameters**
+ `expression1`: The dividend expression.
+ `expression2`: The divisor expression.

## Example (MongoDB Shell)
<a name="mod-examples"></a>

This example demonstrates how to use the `$mod` operator to determine the number of leftover widgets when shipping in packages of 100.

**Create sample documents**

```
db.widgets.insertMany([
  { "_id" : 1, "widget" : "A", "count" : 80372 },
  { "_id" : 2, "widget" : "B", "count" : 409282 },
  { "_id" : 3, "widget" : "C", "count" : 60739 }
])
```

**Query example**

```
db.widgets.aggregate([
  { $addFields: { leftOver: { $mod: [ "$count", 100 ] } } }
])
```

**Output**

```
[
  { "_id" : 1, "widget" : "A", "count" : 80372, "leftOver" : 72 },
  { "_id" : 2, "widget" : "B", "count" : 409282, "leftOver" : 82 },
  { "_id" : 3, "widget" : "C", "count" : 60739, "leftOver" : 39 }
]
```

The output shows the remainder of the `count` divided by 100 for each document, which represents the number of leftover widgets when shipping in packages of 100.

## Code examples
<a name="mod-code"></a>

To view a code example for using the `$mod` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const widgets = db.collection('widgets');

  await widgets.insertMany([
    { "_id" : 1, "widget" : "A", "count" : 80372 },
    { "_id" : 2, "widget" : "B", "count" : 409282 },
    { "_id" : 3, "widget" : "C", "count" : 60739 }
  ]);

  const result = await widgets.aggregate([
    { $addFields: { leftOver: { $mod: [ "$count", 100 ] } } }
  ]).toArray();

  console.log(result);
  client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
widgets = db['widgets']

widgets.insert_many([
    { "_id" : 1, "widget" : "A", "count" : 80372 },
    { "_id" : 2, "widget" : "B", "count" : 409282 },
    { "_id" : 3, "widget" : "C", "count" : 60739 }
])

result = list(widgets.aggregate([
    { "$addFields": { "leftOver": { "$mod": [ "$count", 100 ] } } }
]))

print(result)
client.close()
```

------

# \$1month
<a name="month"></a>

The `$month` operator in Amazon DocumentDB returns the month of a date as a number between 1 and 12. This operator is useful for extracting the month component from a date field and performing date-based aggregations and analyses.

**Parameters**
+ `date_expression`: This is the expression or field that contains the date or timestamp from which you want to extract the month.

## Example (MongoDB Shell)
<a name="month-examples"></a>

The following example demonstrates how to use the `$month` operator to extract the month from a date field and group the data by month.

**Create sample documents**

```
db.sales.insert([
  { product: "abc123", price: 10.99, date: new Date("2022-01-15") },
  { product: "def456", price: 15.50, date: new Date("2022-02-28") },
  { product: "ghi789", price: 8.25, date: new Date("2022-03-10") },
  { product: "jkl012", price: 12.75, date: new Date("2022-04-05") },
  { product: "mno345", price: 18.99, date: new Date("2022-05-20") }
]);
```

**Query example**

```
db.sales.aggregate([
  { $group: { 
      _id: { month: { $month: "$date" } },
      totalSales: { $sum: "$price" }
    }},
  { $sort: { "_id.month": 1 } }
]);
```

**Output**

```
[
  { _id: { month: 1 }, totalSales: 10.99 },
  { _id: { month: 2 }, totalSales: 15.5 },
  { _id: { month: 3 }, totalSales: 8.25 },
  { _id: { month: 4 }, totalSales: 12.75 },
  { _id: { month: 5 }, totalSales: 18.99 }
]
```

## Code examples
<a name="month-code"></a>

To view a code example for using the `$month` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function groupSalesByMonth() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();
    const db = client.db('test');
    const collection = db.collection('sales');

    const pipeline = [
      {
        $group: {
          _id: { month: { $month: "$date" } },
          totalSales: { $sum: "$price" }
        }
      },
      {
        $sort: { "_id.month": 1 }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();

    console.dir(results, { depth: null });

  } finally {
    await client.close();
  }
}

groupSalesByMonth().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def group_sales_by_month():
  
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    try:
        db = client.test
        collection = db.sales

        pipeline = [
            {
                "$group": {
                    "_id": { "$month": "$date" }, 
                    "totalSales": { "$sum": "$price" }  
                }
            },
            {
                "$sort": { "_id": 1 } 
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        client.close()

group_sales_by_month()
```

------

# \$1multiply
<a name="multiply"></a>

The `$multiply` operator in Amazon DocumentDB is used to multiply the values of two or more fields or expressions. This operator is particularly useful for performing arithmetic operations on numeric fields within documents. It can be employed in various stages of the aggregation pipeline, such as `$project` and `$addFields`, to create new fields or modify existing ones.

**Parameters**
+ `expression1`: The first numeric expression to be multiplied.
+ `expression2`: The second numeric expression to be multiplied.
+ `[expression3, ...]`: (optional) Additional numeric expressions to be multiplied.

## Example (MongoDB Shell)
<a name="multiply-examples"></a>

The following example demonstrates using `$multiply` to calculate `bonus_miles` by multiplying `base_miles` and `bonus_rate` for customers who used a credit card for the trip.

**Sample documents**

```
db.miles.insertMany([
{ "_id": 1, "customer_name": "Arnav Desai", "member_since": ISODate("1997-03-01T00:00:00Z"), "base_miles": 2500, "bonus_rate": 1.8, "credit_card": true, "trip_cost": 250 },
{ "_id": 2, "customer_name": "Jorge Souza", "member_since": ISODate("2004-01-10T00:00:00Z"), "base_miles": 1890, "bonus_rate": 1.4, "credit_card": true, "trip_cost": 189 },
{ "_id": 3, "customer_name": "Saanvi Sarkar", "member_since": ISODate("1999-11-22T00:00:00Z"), "base_miles": 3250, "bonus_rate": 1.8, "credit_card": false, "trip_cost": 325 },
{ "_id": 4, "customer_name": "Paulo Santos", "member_since": ISODate("2021-06-19T00:00:00Z"), "base_miles": 2980, "bonus_rate": 1.2, "credit_card": true, "trip_cost": 298 },
{ "_id": 5, "customer_name": "Wang Xiulan", "member_since": ISODate("1995-12-04T00:00:00Z"), "base_miles": 1350, "bonus_rate": 1.9, "credit_card": false, "trip_cost": 135 }
]);
```

**Query example**

```
db.miles.aggregate([
  {
    $match: { credit_card: true }
  },
  {
    $project: {
      customer_name: 1,
      base_miles: 1,
      bonus_rate:1,
      credit_card: 1,
      total_miles: {
        $multiply: ["$base_miles", "$bonus_rate"]
      }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, customer_name: 'Arnav Desai', base_miles: 12500, bonus_rate: 1.8, credit_card: true, total_miles: 22500 },
  { _id: 3, customer_name: 'Saanvi Sarkar',base_miles: 15200, bonus_rate: 1.8, credit_card: true, total_miles: 27360 },
  { _id: 4, customer_name: 'Paulo Santos', base_miles: 3400, bonus_rate: 1.1, credit_card: true, total_miles: 3740 }
]
```

## Code examples
<a name="multiply-code"></a>

To view a code example for using the `$multiply` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function multiplyBonusMiles() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  const result = await collection.aggregate([
    { $match: { credit_card: true } },
    {
      $project: {
        customer_name: 1,
        base_miles: 1,
        bonus_rate: 1,
        credit_card: 1,
        total_miles: {
          $multiply: ["$base_miles", "$bonus_rate"]
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

multiplyBonusMiles();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def multiply_bonus_miles():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['miles']

    result = list(collection.aggregate([
        {'$match': {'credit_card': True}},
        {
            '$project': {
                'customer_name': 1,
                'base_miles': 1,
                'bonus_rate': 1,
                'credit_card': 1,
                'total_miles': {
                    '$multiply': ['$base_miles', '$bonus_rate']
                }
            }
        }
    ]))

    print(result)
    client.close()

multiply_bonus_miles()
```

------

# \$1natural
<a name="natural"></a>

The `$natural` operator in Amazon DocumentDB is used to sort the documents in their natural order, which is the order in which they were inserted into the collection. This is in contrast to the default sorting behavior, which is to sort the documents based on the values of the specified fields.

**Parameters**

None

## Example (MongoDB Shell)
<a name="natural-examples"></a>

The following example demonstrates how to use the `$natural` operator to sort the documents in a collection in their natural order.

**Create sample documents**

```
db.people.insertMany([
  { "_id": 1, "name": "María García", "age": 28 },
  { "_id": 2, "name": "Arnav Desai", "age": 32 },
  { "_id": 3, "name": "Li Juan", "age": 25 },
  { "_id": 4, "name": "Carlos Salazar", "age": 41 },
  { "_id": 5, "name": "Sofia Martínez", "age": 35 }
]);
```

**Query example**

```
db.people.find({}, { "_id": 1, "name": 1 }).sort({ "$natural": 1 });
```

**Output**

```
[
  { "_id": 1, "name": "María García" },
  { "_id": 2, "name": "Arnav Desai" },
  { "_id": 3, "name": "Li Juan" },
  { "_id": 4, "name": "Carlos Salazar" },
  { "_id": 5, "name": "Sofia Martínez" }
]
```

The query sorts the documents in the collection in their natural order, which is the order in which they were inserted.

## Code examples
<a name="natural-code"></a>

To view a code example for using the `$natural` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const documents = await collection.find({}, { projection: { _id: 1, name: 1 } })
    .sort({ $natural: 1 })
    .toArray();

  console.log(documents);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']

    documents = list(collection.find({}, {'_id': 1, 'name': 1}).sort('$natural', 1))
    print(documents)

    client.close()

example()
```

------

# \$1ne
<a name="ne-aggregation"></a>

The `$ne` aggregation operator compares two values and returns `true` if they are not equal, otherwise returns `false`.

**Parameters**
+ `expression1`: The first value to compare.
+ `expression2`: The second value to compare.

## Example (MongoDB Shell)
<a name="ne-aggregation-examples"></a>

The following example demonstrates using the `$ne` operator to identify orders with status changes.

**Create sample documents**

```
db.orders.insertMany([
  { _id: 1, orderId: "A123", status: "shipped", expectedStatus: "shipped" },
  { _id: 2, orderId: "B456", status: "pending", expectedStatus: "shipped" },
  { _id: 3, orderId: "C789", status: "delivered", expectedStatus: "delivered" }
]);
```

**Query example**

```
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      status: 1,
      expectedStatus: 1,
      needsAttention: { $ne: ["$status", "$expectedStatus"] }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, orderId: 'A123', status: 'shipped', expectedStatus: 'shipped', needsAttention: false },
  { _id: 2, orderId: 'B456', status: 'pending', expectedStatus: 'shipped', needsAttention: true },
  { _id: 3, orderId: 'C789', status: 'delivered', expectedStatus: 'delivered', needsAttention: false }
]
```

## Code examples
<a name="ne-aggregation-code"></a>

To view a code example for using the `$ne` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $project: {
        orderId: 1,
        status: 1,
        expectedStatus: 1,
        needsAttention: { $ne: ["$status", "$expectedStatus"] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.aggregate([
        {
            '$project': {
                'orderId': 1,
                'status': 1,
                'expectedStatus': 1,
                'needsAttention': { '$ne': ['$status', '$expectedStatus'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1not
<a name="not-aggregation"></a>

The `$not` aggregation operator performs a logical NOT operation on an expression. It returns `true` if the expression evaluates to `false`, and `false` if the expression evaluates to `true`.

**Parameters**
+ `expression`: The expression to negate.

## Example (MongoDB Shell)
<a name="not-aggregation-examples"></a>

The following example demonstrates using the `$not` operator to invert boolean values.

**Create sample documents**

```
db.users.insertMany([
  { _id: 1, name: "Alice", active: true },
  { _id: 2, name: "Bob", active: false },
  { _id: 3, name: "Charlie", active: true }
]);
```

**Query example**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      active: 1,
      inactive: { $not: ["$active"] }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, name: 'Alice', active: true, inactive: false },
  { _id: 2, name: 'Bob', active: false, inactive: true },
  { _id: 3, name: 'Charlie', active: true, inactive: false }
]
```

## Code examples
<a name="not-aggregation-code"></a>

To view a code example for using the `$not` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        active: 1,
        inactive: { $not: ["$active"] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'active': 1,
                'inactive': { '$not': ['$active'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1objectToArray
<a name="objectToArray"></a>

The `$objectToArray` aggregation operator in Amazon DocumentDB converts an object (or document) into an array. The input to the operator is a document, and the output consists of an array element for each field-value pair in the input document. This operator is useful when you need to work with the individual fields of a document as an array, such as when you want to find the document with the maximum or minimum value for a particular field.

**Parameters**
+ `expression`: The document expression to convert into an array.

## Example (MongoDB Shell)
<a name="objectToArray-examples"></a>

The following example demonstrates how to use the `$objectToArray` operator to find the document with the maximum inventory for a video rental store chain.

**Create sample documents**

```
db.videos.insertMany([
  {
    "_id": 1,
    "name": "Live Soft",
    "inventory": {
      "Des Moines": 1000,
      "Ames": 500
    }
  },
  {
    "_id": 2,
    "name": "Top Pilot",
    "inventory": {
      "Mason City": 250,
      "Des Moines": 1000
    }
  },
  {
    "_id": 3,
    "name": "Romancing the Rock",
    "inventory": {
      "Mason City": 250,
      "Ames": 500
    }
  },
  {
    "_id": 4,
    "name": "Bravemind",
    "inventory": {
      "Mason City": 250,
      "Des Moines": 1000,
      "Ames": 500
    }
  }
]);
```

**Query example**

```
db.videos.aggregate([
  {
    $project: {
      name: 1,
      videos: {
        $objectToArray: "$inventory"
      }
    }
  },
  {
    $unwind: "$videos"
  },
  {
    $group: {
      _id: "$name",
      maxInventory: {
        $max: "$videos.v"
      }
    }
  }
]);
```

**Output**

```
[
  {
    "_id": "Bravemind",
    "maxInventory": 1000
  },
  {
    "_id": "Live Soft",
    "maxInventory": 1000
  },
  {
    "_id": "Romancing the Rock",
    "maxInventory": 500
  },
  {
    "_id": "Top Pilot",
    "maxInventory": 1000
  }
]
```

## Code examples
<a name="objectToArray-code"></a>

To view a code example for using the `$objectToArray` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findMaxInventory() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const videos = db.collection('videos');

  const result = await videos.aggregate([
    {
      $project: {
        name: 1,
        videos: {
          $objectToArray: "$inventory"
        }
      }
    },
    {
      $unwind: "$videos"
    },
    {
      $group: {
        _id: "$name",
        maxInventory: {
          $max: "$videos.v"
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

findMaxInventory();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_max_inventory():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    videos = db['videos']

    result = list(videos.aggregate([
        {
            '$project': {
                'name': 1,
                'videos': {
                    '$objectToArray': '$inventory'
                }
            }
        },
        {
            '$unwind': '$videos'
        },
        {
            '$group': {
                '_id': '$name',
                'maxInventory': {
                    '$max': '$videos.v'
                }
            }
        }
    ]))

    print(result)
    client.close()

find_max_inventory()
```

------

# \$1or
<a name="or-aggregation"></a>

The `$or` aggregation operator evaluates multiple expressions and returns `true` if at least one expression evaluates to `true`. It returns `false` only if all expressions are `false`.

**Parameters**
+ `expressions`: An array of expressions to evaluate.

## Example (MongoDB Shell)
<a name="or-aggregation-examples"></a>

The following example demonstrates using the `$or` operator to check if products meet any of multiple criteria.

**Create sample documents**

```
db.items.insertMany([
  { _id: 1, name: "Widget", price: 150, onSale: false },
  { _id: 2, name: "Gadget", price: 45, onSale: false },
  { _id: 3, name: "Tool", price: 200, onSale: true }
]);
```

**Query example**

```
db.items.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      onSale: 1,
      goodDeal: {
        $or: [
          { $lt: ["$price", 50] },
          { $eq: ["$onSale", true] }
        ]
      }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, name: 'Widget', price: 150, onSale: false, goodDeal: false },
  { _id: 2, name: 'Gadget', price: 45, onSale: false, goodDeal: true },
  { _id: 3, name: 'Tool', price: 200, onSale: true, goodDeal: true }
]
```

## Code examples
<a name="or-aggregation-code"></a>

To view a code example for using the `$or` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('items');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        price: 1,
        onSale: 1,
        goodDeal: {
          $or: [
            { $lt: ["$price", 50] },
            { $eq: ["$onSale", true] }
          ]
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['items']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'price': 1,
                'onSale': 1,
                'goodDeal': {
                    '$or': [
                        { '$lt': ['$price', 50] },
                        { '$eq': ['$onSale', True] }
                    ]
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1out
<a name="out"></a>

The `$out` operator in Amazon DocumentDB is used to write the result of an aggregation pipeline to a specified collection.

`$out` should be the last stage in the pipeline.

**Parameters**
+ `output_collection`: The name of the output collection to write the aggregation results to.

**Note**: If the collection already exists, it will be replaced with the results of the aggregation stage.

## Example (MongoDB Shell)
<a name="out-examples"></a>

The following example demonstrates how to use the `$out` operator in Amazon DocumentDB to write the results of an aggregation pipeline to a new collection.

**Create sample documents**

```
db.products.insertMany([
  { _id: 1, name: "Wireless Headphones", category: "Electronics", price: 100.0 },
  { _id: 2, name: "Smartphone", category: "Electronics", price: 200.0 },
  { _id: 3, name: "JavaScript Guide", category: "Books", price: 50.0 },
  { _id: 4, name: "Database Design Handbook", category: "Books", price: 75.0 }
]);
```

**Query example**

```
db.products.aggregate([
  { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
  { $out: "product_categories" }
])
```

**Output**

None (the results are written to the output collection).

The aggregation pipeline groups the products by category and calculates the total price of the items for each category. The `$out` operator writes the results to a new collection named "product\$1categories".

**To view the results in the output collection:**

```
db.product_categories.find()
[
{ "_id" : "Books", "totalPrice" : 125 },
{ "_id" : "Electronics", "totalPrice" : 300 }
]
```

## Code examples
<a name="out-code"></a>

To view a code example for using the `$out` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function demo_out_operator() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const products = db.collection('products');

  // Execute aggregation with $out - results are stored in 'product_categories' collection
  await products.aggregate([
    { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
    { $out: "product_categories" }
  ]).toArray();

  // Retrieve the results from the output collection (limited to 20 records)
  const productCategories = db.collection('product_categories');
  const results = await productCategories.find({}).limit(20).toArray();
  
  console.log('Results stored in product_categories collection:', results);
  await client.close();
}

demo_out_operator();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def demo_out_operator():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    products = db['products']

    # Execute aggregation with $out - results are stored in 'product_categories' collection
    list(products.aggregate([
        { '$group': { '_id': '$category', 'totalPrice': { '$sum': '$price' } } },
        { '$out': 'product_categories' }
    ]))

    # Retrieve the results from the output collection (limited to 20 records)
    product_categories = db['product_categories']
    results = list(product_categories.find({}).limit(20))
    
    print('Results stored in product_categories collection:', results)
    client.close()

demo_out_operator()
```

------

# \$1pow
<a name="pow"></a>

Introduced in 8.0

The `$pow` operator in Amazon DocumentDB allows you to raise a number to a power. This can be useful for performing exponential calculations within your aggregation pipeline.

**Parameters**
+ `<number>` (required): The number to be raised to a power.
+ `<exponent>` (required): The power to which the number should be raised.

## Example (MongoDB Shell)
<a name="pow-examples"></a>

The following example demonstrates how to use the `$pow` operator to calculate the square of a number.

**Create sample documents**

```
db.numbers.insertMany([
  { "_id": 1, "value": 2 },
  { "_id": 2, "value": 3 },
  { "_id": 3, "value": 4 }
]);
```

**Query example**

```
db.numbers.aggregate([
  { $addFields: { "square": { $pow: ["$value", 2] } } }
])
```

**Output**

```
[
  { "_id": 1, "value": 2, "square": 4 },
  { "_id": 2, "value": 3, "square": 9 },
  { "_id": 3, "value": 4, "square": 16 }
]
```

## Code examples
<a name="pow-code"></a>

To view a code example for using the `$pow` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of using the \$1pow operator in a Node.js application:

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $addFields: { "square": { $pow: ["$value", 2] } } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

Here's an example of using the \$1pow operator in a Python application:

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        { "$addFields": { "square": { "$pow": ["$value", 2] } } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1push
<a name="push-aggregation"></a>

The `$push` aggregation operator returns an array of all values from a specified expression for each group. It is typically used within the `$group` stage to accumulate values into an array.

**Parameters**
+ `expression`: The expression to evaluate for each document in the group.

## Example (MongoDB Shell)
<a name="push-aggregation-examples"></a>

The following example demonstrates using the `$push` operator to collect all product names for each category.

**Create sample documents**

```
db.sales.insertMany([
  { _id: 1, category: "Electronics", product: "Laptop", amount: 1200 },
  { _id: 2, category: "Electronics", product: "Mouse", amount: 25 },
  { _id: 3, category: "Furniture", product: "Desk", amount: 350 },
  { _id: 4, category: "Furniture", product: "Chair", amount: 150 },
  { _id: 5, category: "Electronics", product: "Keyboard", amount: 75 }
]);
```

**Query example**

```
db.sales.aggregate([
  {
    $group: {
      _id: "$category",
      products: { $push: "$product" }
    }
  }
]);
```

**Output**

```
[
  { _id: 'Furniture', products: [ 'Desk', 'Chair' ] },
  { _id: 'Electronics', products: [ 'Laptop', 'Mouse', 'Keyboard' ] }
]
```

## Code examples
<a name="push-aggregation-code"></a>

To view a code example for using the `$push` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('sales');

  const result = await collection.aggregate([
    {
      $group: {
        _id: "$category",
        products: { $push: "$product" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['sales']

    result = list(collection.aggregate([
        {
            '$group': {
                '_id': '$category',
                'products': { '$push': '$product' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1project
<a name="project"></a>

The `$project` operator in Amazon DocumentDB allows you to selectively include or exclude fields from output documents, pass values to the next pipeline stage, and compute new fields from input document values.

**Parameters**
+ `field`: The field to include or exclude from the output documents, it can be a field path (e.g., "a.b.c").
+ `1` or `true`: Includes the field in the output.
+ `0` or `false`: Excludes the field from the output.

## Example (MongoDB Shell)
<a name="project-examples"></a>

The following example demonstrates the usage of the `$project` operator on students collection

**Create sample documents**

```
db.students.insertMany([
  { "_id": 1, "name": "Alejandro Rosalez", "math": 85, "science": 92, "grade": "A" },
  { "_id": 2, "name": "Carlos Salazar", "math": 78, "science": 84, "grade": "B" },
  { "_id": 3, "name": "Nikhil Jayashankar", "math": 95, "science": 89, "grade": "A" },
  { "_id": 4, "name": "Shirley Rodriguez", "math": 72, "science": 76, "grade": "B" }
  ]);
```

This query includes only the `name` and `math` fields in the output. The `_id` field is included by default unless explicitly excluded.

```
db.students.aggregate([
  { $project: { "name": 1, "math": 1 } }
])
```

**Output**

```
{ _id: 1, name: "Alejandro Rosalez", math: 85 }
{ _id: 2, name: "Carlos Salazar", math: 78 }
{ _id: 3, name: "Nikhil Jayashankar", math: 95 }
{ _id: 4, name: "Shirley Rodriguez", math: 72 }
```

This query excludes the `grade` and `_id` fields from the output, showing all other fields (`name`, `math`, `science`).

```
db.students.aggregate([
  { $project: { "grade": 0, "_id": 0 } }
])
```

**Output**

```
{ name: "Alejandro Rosalez", math: 85, science: 92 }
{ name: "Carlos Salazar", math: 78, science: 84 }
{ name: "Nikhil Jayashankar", math: 95, science: 89 }
{ name: "Shirley Rodriguez", math: 72, science: 76 }
```

## Code examples
<a name="project-code"></a>

To view a code example for using the `$project` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  const result = await collection.aggregate([
    { $project: { "name": 1, "math": 1 } }
  ]).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['students']

    result = list(collection.aggregate([
        { '$project': { 'name': 1, 'math': 1 } }
    ]))
    print(result)

    client.close()

example()
```

------

# \$1rand
<a name="rand"></a>

New from version 8.0

The `$rand` operator in Amazon DocumentDB is used to generate a random number between 0 and 1.

**Parameters**

None

## Example (MongoDB Shell)
<a name="rand-examples"></a>

The following example demonstrates how to use the `$rand` operator to randomly select two documents from the `temp` collection.

**Create sample documents**

```
db.items.insertMany([
  { "name": "pencil", "quantity": 110 },
  { "name": "pen", "quantity": 159 }
])
```

**Query example**

```
db.items.aggregate([
  {
    $project: {
      randomValue: { $rand: {} }
    }
  }
])
```

**Output**

```
[
  {
    _id: ObjectId('6924a5edd66dcae121d29517'),
    randomValue: 0.8615243955294392
  },
  {
    _id: ObjectId('6924a5edd66dcae121d29518'),
    randomValue: 0.22815483022099903
  }
]
```

## Code examples
<a name="rand-code"></a>

To view a code example for using the `$rand` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('items');

  const result = await collection.aggregate([
    {
      $project: {
        randomValue: { $rand: {} }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
  db = client['test']
  collection = db['items']

  result = list(collection.aggregate([
      {
        "$project": {
          "randomValue": { "$rand": {} }
        }
      }
  ]))

  print(result)

  client.close()

example()
```

------

# \$1range
<a name="range"></a>

The `$range` aggregation operator in Amazon DocumentDB is used to create an array of consecutive numbers within a specified range. This operator is particularly useful for generating sequences of numbers, such as mile markers for aid stations in a race, as demonstrated in the examples below.

**Parameters**
+ `start`: The starting value for the range.
+ `end`: The ending value for the range.
+ `step`: (optional) The step value to use when generating the range. If not provided, the default step value is 1.

## Example (MongoDB Shell)
<a name="range-examples"></a>

In this example, we'll use the `$range` operator to generate the mile markers for water stations in a bicycle race.

**Create sample documents**

```
db.races.insertMany([
  { _id: 0, race: "STP", distance: 206 },
  { _id: 1, race: "RSVP", distance: 160 },
  { _id: 2, race: "Chilly Hilly", distance: 33 },
  { _id: 3, race: "Flying Wheels", distance: 100 }
]);
```

**Query example**

```
db.races.aggregate([
  {
    $project: {
      race: 1,
      "waterStations": { $range: [20, "$distance", 20] }
    }
  }
]);
```

**Output**

```
[
  {
    _id: 0,
    race: 'STP',
    waterStations: [
       20,  40,  60,  80,
      100, 120, 140, 160,
      180, 200
    ]
  },
  {
    _id: 1,
    race: 'RSVP',
    waterStations: [
       20,  40,  60, 80,
      100, 120, 140
    ]
  },
  { _id: 2, race: 'Chilly Hilly', waterStations: [ 20 ] },
  { _id: 3, race: 'Flying Wheels', waterStations: [ 20, 40, 60, 80 ] }
]
```

## Code examples
<a name="range-code"></a>

To view a code example for using the `$range` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();
    const db = client.db('test');
    const collection = db.collection('races');

    const pipeline = [
      {
        $project: {
          race: 1,
          waterStations: { $range: [20, "$distance", 20] } 
        }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();

    console.dir(results, { depth: null });

  } finally {
    await client.close();
  }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():

  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

  try:
      db = client.test
      collection = db.races

      pipeline = [
          {
              "$project": {
                  "race": 1,
                  "waterStations": { "$range": [20, "$distance", 20] }
              }
          }
      ]

      results = collection.aggregate(pipeline)

      for doc in results:
          print(doc)

  except Exception as e:
      print(f"An error occurred: {e}")

  finally:
      client.close()

example()
```

------

# \$1redact
<a name="redact"></a>

The `$redact` aggregation stage in Amazon DocumentDB is used to selectively include or exclude content from the output documents based on the values of specified fields. This is particularly useful in scenarios where you need to control the visibility of sensitive data based on access levels or user permissions.

**Parameters**
+ `$cond`: An expression that evaluates to either `$$KEEP`, `$$PRUNE`, or `$$DESCEND` for each field in the document.
+ `$$KEEP`: Retains the current field in the output document.
+ `$$PRUNE`: Removes the current field from the output document.
+ `$$DESCEND`: Recursively applies the `$redact` stage to the current field, which is an object or array.

## Example (MongoDB Shell)
<a name="redact-examples"></a>

In this example, we'll use the `$redact` stage to filter orders based on their status, showing only orders with specific status values.

**Create sample documents**

```
db.orders.insert([
  { "_id": 1, "status": "shipped", "customer": "Carlos Salazar", "total": 150.00, "date": "2025-01-15" },
  { "_id": 2, "status": "processing", "customer": "Saanvi Sarkar", "total": 89.99, "date": "2025-01-20" },
  { "_id": 3, "status": "cancelled", "customer": "Zhang Wei", "total": 220.50, "date": "2025-01-18" }
])
```

**Query example**

```
db.orders.aggregate([
  {
    $redact: {
      $cond: {
        if: { $in: ["$status", ["shipped", "processing"]] },
        then: "$$KEEP",
        else: "$$PRUNE"
      }
    }
  }
])
```

**Output**

```
[
  { _id: 1, status: 'shipped', customer: 'Carlos Salazar', total: 150, date: '2025-01-15' },
  { _id: 2, status: 'processing', customer: 'Saanvi Sarkar', total: 89.99, date: '2025-01-20' }
]
```

In this example, the `$redact` stage checks the value of the `status` field in each document. If the `status` is "shipped" or "processing", the document is kept (`$$KEEP`). Otherwise, the document is pruned (`$$PRUNE`).

## Code examples
<a name="redact-code"></a>

To view a code example for using the `$redact` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $redact: {
        $cond: {
          if: { $in: ['$status', ['shipped', 'processing']] },
          then: '$$KEEP',
          else: '$$PRUNE'
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.aggregate([
        {
            '$redact': {
                '$cond': {
                    'if': { '$in': ['$status', ['shipped', 'processing']] },
                    'then': '$$KEEP',
                    'else': '$$PRUNE'
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1reduce
<a name="reduce"></a>

The `$reduce` aggregation operator in Amazon DocumentDB is used to apply a function of two arguments cumulatively to the elements of an array to reduce the array to a single value. This operator is particularly useful for performing complex calculations or transformations on array data within the aggregation pipeline.

**Parameters**
+ `input`: The array to be reduced.
+ `initialValue`: The initial value to be used in the reduction operation.
+ `in`: The expression to be evaluated on each element of the `input` array. This expression should return a value that will be used in the next iteration of the reduction.

## Example (MongoDB Shell)
<a name="reduce-examples"></a>

The following example demonstrates how to use the `$reduce` operator to calculate the sum of all elements in an array.

**Create sample documents**

```
db.orders.insertMany([
  { "_id": 1, "items": [1, 2, 3, 4, 5] },
  { "_id": 2, "items": [10, 20, 30] },
  { "_id": 3, "items": [5, 15, 25, 35] },
  { "_id": 4, "items": [100, 200] }
])
```

**Query example**

```
db.orders.aggregate([
  {
    $project: {
      total: {
        $reduce: {
          input: "$items",
          initialValue: 0,
          in: { $add: ["$$value", "$$this"] }
        }
      }
    }
  }
])
```

**Output**

```
[
  { "_id": 1, "total": 15 },
  { "_id": 2, "total": 60 },
  { "_id": 3, "total": 80 },
  { "_id": 4, "total": 300 }
]
```

The `$reduce` operator iterates over the `items` array, adding each element to the `initialValue` of 0. The result is the sum of all elements in the array.

## Code examples
<a name="reduce-code"></a>

To view a code example for using the `$reduce` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of using the `$reduce` operator in a Node.js application:

```
const { MongoClient } = require("mongodb");

async function main() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const orders = db.collection("orders");

  const result = await orders.aggregate([
    {
      $project: {
        total: {
          $reduce: {
            input: "$items",
            initialValue: 0,
            in: { $add: ["$$value", "$$this"] }
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

Here's an example of using the `$reduce` operator in a python application:

```
from pymongo import MongoClient

def main():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    orders = db["orders"]

    result = list(orders.aggregate([
        {
            "$project": {
                "total": {
                    "$reduce": {
                        "input": "$items",
                        "initialValue": 0,
                        "in": { "$add": ["$$value", "$$this"] }
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1regexFind
<a name="regexFind"></a>

New from version 5.0.

Not supported by Elastic cluster.

The `$regexFind` operator in Amazon DocumentDB is used to perform regular expression matching on string fields within documents. It allows you to search for and extract specific substrings that match a given regular expression pattern.

**Parameters**
+ `input`: The string field or expression to search.
+ `regex`: The regular expression pattern to match.
+ `options`: (optional) An object that specifies optional parameters for the regular expression, such as case-sensitivity and multi-line matching. Supported options are `i` (case-insensitive) and `m` (multi-line).

## Example (MongoDB Shell)
<a name="regexFind-examples"></a>

The following example demonstrates how to use the `$regexFind` operator to search for documents where the `name` field matches a specific regular expression pattern.

**Create sample documents**

```
db.users.insertMany([
  { "_id": 1, name: "John Doe", email: "john@example.com" },
  { "_id": 2, name: "Diego Ramirez", email: "diego@example.com" },
  { "_id": 3, name: "Alejandro Rosalez", email: "alejandro@example.com" },
  { "_id": 4, name: "Shirley Rodriguez", email: "shirley@example.com" }
]);
```

**Query example**

```
db.users.aggregate([
  {
    $project: {
      names: {
        $regexFind: { input: '$name', regex: 'j', options: 'i' }
      }
    }
  },
  { $match: {names: {$ne: null}}}
])
```

This query will return all documents where the `name` field contains the letter "j" (case-insensitive).

**Output**

```
[
  { _id: 1, names: { match: 'J', idx: 0, captures: [] } }
]
```

**Note:** If your query is using Amazon DocumentDB planner version 1, you must use a hint to utilize an index. Without a hint, the query may perform a collection scan. To check your planner version and learn more about using hints, see the [Amazon DocumentDB Query Planner documentation](https://docs.aws.amazon.com/documentdb/latest/developerguide/query-planner.html).

## Code examples
<a name="regexFind-code"></a>

To view a code example for using the `$regexFind` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const results = await users.aggregate([
    { $project: { names: { $regexFind: { input: "$name", regex: "john", options: "i" }}}},
    { $match: {names: {$ne: null}}}
  ]).toArray();
  

  console.log(results);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']

results = list(users.aggregate([
    { "$project": { "names": { "$regexFind": { "input": "$name", "regex": "john", "options": "i" }}}},
    { "$match": {"names": {"$ne": None}}}
]))

print(results)

client.close()
```

------

# \$1regexFindAll
<a name="regexFindAll"></a>

Introduced in 5.0

The `$regexFindAll` operator in Amazon DocumentDB is used to perform regular expression matching on string fields within documents. It allows you to search for and extract specific substrings that match a given regular expression pattern, returning all matches of the regular expression.

**Parameters**
+ `input`: The string field or expression to search.
+ `regex`: The regular expression pattern to match.
+ `options`: (optional) An object that specifies optional parameters for the regular expression, such as case-sensitivity and multi-line matching. Supported options are `i` (case-insensitive) and `m` (multi-line).

## Example (MongoDB Shell)
<a name="regexFindAll-examples"></a>

The following example demonstrates how to use the `$regexFindAll` operator to extract all letter sequences from the `email` field.

**Create sample documents**

```
db.users.insertMany([
  { _id: 1, name: "John Doe", email: "john@example.com", phone: "555-1234" },
  { _id: 2, name: "Jane Roe", email: "jane@example.com", phone: "555-5678" },
  { _id: 3, name: "Carlos Salazar", email: "carlos@example.com", phone: "555-3456" },
  { _id: 4, name: "Saanvi Sarkar", email: "saanvi@example.com", phone: "555-7890" }
  
]);
```

**Query example**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      emailMatches: {
        $regexFindAll: { input: '$email', regex: '[a-z]+', options: 'i' }
      }
    }
  }
])
```

**Output**

```
[
  {
    _id: 1,
    name: 'John Doe',
    emailMatches: [
      { match: 'john', idx: 0, captures: [] },
      { match: 'example', idx: 5, captures: [] },
      { match: 'com', idx: 13, captures: [] }
    ]
  },
  {
    _id: 2,
    name: 'Jane Roe',
    emailMatches: [
      { match: 'jane', idx: 0, captures: [] },
      { match: 'example', idx: 5, captures: [] },
      { match: 'com', idx: 13, captures: [] }
    ]
  },
  {
    _id: 3,
    name: 'Carlos Salazar',
    emailMatches: [
      { match: 'carlos', idx: 0, captures: [] },
      { match: 'example', idx: 7, captures: [] },
      { match: 'com', idx: 15, captures: [] }
    ]
  },
  {
    _id: 4,
    name: 'Saanvi Sarkar',
    emailMatches: [
      { match: 'saanvi', idx: 0, captures: [] },
      { match: 'example', idx: 7, captures: [] },
      { match: 'com', idx: 15, captures: [] }
    ]
  }
]
```

**Note:** If your query is using Amazon DocumentDB planner version 1, you must use a hint to utilize an index. Without a hint, the query may perform a collection scan. To check your planner version and learn more about using hints, see the [Amazon DocumentDB Query Planner documentation](https://docs.aws.amazon.com/documentdb/latest/developerguide/query-planner.html).

## Code examples
<a name="regexFindAll-code"></a>

To view a code example for using the `$regexFindAll` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of using the `$regexFind` operator in a Node.js application:

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const results = await users.aggregate([
    {
      $project: {
        name: 1,
        emailMatches: {
          $regexFindAll: { input: "$email", regex: "[a-z]+", options: "i" }
        }
      }
    }
  ]).toArray();
  
  console.log(JSON.stringify(results, null, 2));

  await client.close();
}

main();
```

------
#### [ Python ]

Here's an example of using the `$regexFind` operator in a Python application:

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']

results = list(users.aggregate([
    { 
        "$project": { 
            "name": 1,
            "emailMatches": { 
                "$regexFindAll": { 
                    "input": "$email", 
                    "regex": "[a-z]+", 
                    "options": "i" 
                }
            }
        }
    }
]))

print(results)

client.close()
```

------

# \$1regexMatch
<a name="regexMatch"></a>

New from version 5.0. Not supported by Elastic cluster.

The `$regexMatch` operator in Amazon DocumentDB is used to perform regular expression matching on string fields. It returns a boolean value (`true` or `false`) indicating whether the input string matches the specified pattern.

**Parameters**
+ `input`: The string to test against the regular expression.
+ `regex`: The regular expression pattern to match.
+ `options`: (Optional) Flags to modify the regular expression behavior, such as case-insensitive matching (`i`) or multiline matching (`m`).

## Example (MongoDB Shell)
<a name="regexMatch-examples"></a>

The following example demonstrates how to use the `$regexMatch` operator to check if names start with the letter 'M'. The operator returns `true` or `false` for each document.

**Create sample documents**

```
db.users.insertMany([
  { "_id":1, name: "María García", email: "maría@example.com" },
  { "_id":2, name: "Arnav Desai", email: "arnav@example.com" },
  { "_id":3, name: "Martha Rivera", email: "martha@example.com" },
  { "_id":4, name: "Richard Roe", email: "richard@example.com" },

]);
```

**Query example**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      startsWithM: {
        $regexMatch: {
          input: "$name",
          regex: "^M",
          options: "i"
        }
      }
    }
  }
]);
```

**Output**

```
{ _id: 1, name: 'María García', startsWithM: true },
{ _id: 2, name: 'Arnav Desai', startsWithM: false },
{ _id: 3, name: 'Martha Rivera', startsWithM: true },
{ _id: 4, name: 'Richard Roe', startsWithM: false }
```

## Code examples
<a name="regexMatch-code"></a>

To view a code example for using the `$regexMatch` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function checkNamePattern() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        startsWithM: {
          $regexMatch: {
            input: "$name",
            regex: "^M",
            options: "i"
          }
        }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

checkNamePattern();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def check_name_pattern():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.users

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'startsWithM': {
                    '$regexMatch': {
                        'input': '$name',
                        'regex': '^M',
                        'options': 'i'
                    }
                }
            }
        }
    ]))

    print(result)

    client.close()

check_name_pattern()
```

------

# \$1replaceAll
<a name="replaceAll"></a>

Introduced in 5.0

The `$replaceAll` operator in Amazon DocumentDB is used to replace all occurrences of a specified string pattern within a field with a new string. This operator can be useful for tasks such as data normalization, text cleaning, and string manipulation.

**Parameters**
+ `input`: The field or expression containing the string to be replaced.
+ `find`: The string pattern to search for and replace.
+ `replacement`: The string to replace the matched occurrences with.

## Example (MongoDB Shell)
<a name="replaceAll-examples"></a>

The following example demonstrates how to use the `$replaceAll` operator in an aggregation pipeline to replace all occurrences of the string "Chocolatier" with "Chocolate Co." in the "brandName" field of a "products" collection.

**Create sample documents**

```
db.products.insertMany([
  {
    "_id": 1,
    "productId": "PROD-0Y9GL0",
    "brandName": "Gordon's Chocolatier",
    "category": "CPG",
    "rating": {
      "average": 4.8
    }
  },
  {
    "_id": 2,
    "productId": "PROD-1X2YZ3",
    "brandName": "Premium Chocolatier",
    "category": "CPG",
    "rating": {
      "average": 4.5
    }
  },
  {
    "_id": 3,
    "productId": "PROD-Y2E9H5",
    "name": "Nutrition Co. - Original Corn Flakes Cereal",
    "category": "Breakfast Cereals",
    "price": 8.5
  }
]);
```

**Query example**

```
db.products.aggregate([
  {
    $addFields: {
      "brandName": {
        $replaceAll: {
          input: "$brandName",
          find: "Chocolatier",
          replacement: "Chocolate Co."
        }
      }
    }
  }
])
```

**Output**

```
[
  {
    _id: 1,
    productId: 'PROD-0Y9GL0',
    brandName: "Gordon's Chocolate Co.",
    category: 'CPG',
    rating: { average: 4.8 }
  },
  {
    _id: 2,
    productId: 'PROD-1X2YZ3',
    brandName: 'Premium Chocolate Co.',
    category: 'CPG',
    rating: { average: 4.5 }
  },
  {
    _id: 3,
    productId: 'PROD-Y2E9H5',
    name: 'Nutrition Co. - Original Corn Flakes Cereal',
    category: 'Breakfast Cereals',
    price: 8.5,
    brandName: null
  }
]
```

## Code examples
<a name="replaceAll-code"></a>

To view a code example for using the `$replaceAll` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function replaceAll() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const results = await collection.aggregate([
    {
      $addFields: {
        "brandName": {
          $replaceAll: {
            input: "$brandName",
            find: "Chocolatier",
            replacement: "Chocolate Co."
          }
        }
      }
    }
  ]).toArray();

  console.log(results);

  await client.close();
}

replaceAll();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def replace_all():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    results = list(collection.aggregate([
        {
            "$addFields": {
                "brandName": {
                    "$replaceAll": {
                        "input": "$brandName",
                        "find": "Chocolatier",
                        "replacement": "Chocolate Co."
                    }
                }
            }
        }
    ]))

    print(results)

    client.close()

replace_all()
```

------

# \$1replaceOne
<a name="replaceOne"></a>

Introduced in 5.0

The `$replaceOne` operator in Amazon DocumentDB is a string expression operator used within aggregation pipelines to replace the first occurrence of a specified substring within a string with a replacement string. This operator is case-sensitive and only replaces the first match found.

**Parameters**
+ `input`: The string (field) on which to perform the find.
+ `find`: The string to search for within the input.
+ `replacement`: The string to replace the first occurrence of the find in the input(field).

## Example (MongoDB Shell)
<a name="replaceOne-examples"></a>

The following example demonstrates how to use the `$replaceOne` operator within an aggregation pipeline to replace substrings in product names.

**Create sample documents**

```
db.products.insertMany([
  { "_id":1, "productId": "PROD-0Y9GL0", "name": "Gordon's Extra Creamy Milk Chocolate - Pack of 4", "category": "Confectionery", "price": 24.99 },
  { "_id":2, "productId": "PROD-Y2E9H5", "name": "Nutrition Co. - Original Corn Flakes Cereal", "category": "Breakfast Cereals", "price": 8.50 },
  { "_id":3, "productId": "PROD-Z3F8K2", "name": "Gordon's Dark Chocolate (90% Cocoa) Pack - Pack of 4", "category": "Confectionery", "price": 28.99 }
]);
```

**Aggregation example**

```
db.products.aggregate([
  {
    $addFields: {
      standardizedName: {
        $replaceOne: {
          input: "$name",
          find: "Pack",
          replacement: "Package"
        }
      }
    }
  }
]);
```

**Output**

The output shows that only the first occurrence of "Pack" in each product name was replaced with "Package".

```
[
  {
    _id: 1,
    productId: 'PROD-0Y9GL0',
    name: "Gordon's Extra Creamy Milk Chocolate - Pack of 4",
    category: 'Confectionery',
    price: 24.99,
    standardizedName: "Gordon's Extra Creamy Milk Chocolate - Package of 4"
  },
  {
    _id: 2,
    productId: 'PROD-Y2E9H5',
    name: 'Nutrition Co. - Original Corn Flakes Cereal',
    category: 'Breakfast Cereals',
    price: 8.5,
    standardizedName: 'Nutrition Co. - Original Corn Flakes Cereal'
  },
  {
    _id: 3,
    productId: 'PROD-Z3F8K2',
    name: "Gordon's Dark Chocolate (90% Cocoa) Pack - Pack of 4",
    category: 'Confectionery',
    price: 28.99,
    standardizedName: "Gordon's Dark Chocolate (90% Cocoa) Package - Pack of 4"
  }
```

## Code examples
<a name="replaceOne-code"></a>

To view a code example for using the `$replaceOne` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function replaceOne() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const pipeline = [
    {
      $addFields: {
        standardizedName: {
          $replaceOne: {
            input: '$name',
            find: 'Pack',
            replacement: 'Package'
          }
        }
      }
    }
  ];

  const result = await collection.aggregate(pipeline).toArray();
  console.log(result);

  await client.close();
}

replaceOne();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def replaceOne():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    pipeline = [
        {
            '$addFields': {
                'standardizedName': {
                    '$replaceOne': {
                        'input': '$name',
                        'find': 'Pack',
                        'replacement': 'Package'
                    }
                }
            }
        }
    ]

    result = list(collection.aggregate(pipeline))
    print(result)

    client.close()

replaceOne()
```

------

# \$1replaceRoot
<a name="replaceRoot"></a>

The `$replaceRoot` operator is used to replace the root document with the specified embedded document. This is useful when you want to promote a nested document to the top level or restructure your data output.

**Parameters**
+ `newRoot`: The new root document that will replace the existing root document.

## Example (MongoDB Shell)
<a name="replaceRoot-examples"></a>

This example shows how to extract shipping address information from customer orders, which is useful for generating shipping labels or address lists.

**Create sample documents**

```
db.orders.insertMany([
  {
    "_id":1, "orderId": "ORD-2024-001", "customerId": "CUST-12345", "orderDate": "2024-01-15", "shippingAddress": { "name": "María García", "street": "123 Main St", "city": "Seattle", "state": "WA", "zipCode": "98101", "country": "USA" },"totalAmount": 149.99 },
  { "_id":2, "orderId": "ORD-2024-002", "customerId": "CUST-67890", "orderDate": "2024-01-16", "shippingAddress": { "name": "Arnav Desai", "street": "456 Oak Ave", "city": "Portland", "state": "OR", "zipCode": "97201", "country": "USA" }, "totalAmount": 89.50 } ])
```

**Query example**

```
db.orders.aggregate([
  {
    $replaceRoot: {
      newRoot: "$shippingAddress"
    }
  }
])
```

**Output**

```
{
    name: 'María García',
    street: '123 Main St',
    city: 'Seattle',
    state: 'WA',
    zipCode: '98101',
    country: 'USA'
  },
  {
    name: 'Arnav Desai',
    street: '456 Oak Ave',
    city: 'Portland',
    state: 'OR',
    zipCode: '97201',
    country: 'USA'
  }
```

## Code examples
<a name="replaceRoot-code"></a>

To view a code example for using the `$replaceRoot` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function extractShippingAddresses() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $replaceRoot: {
        newRoot: "$shippingAddress"
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

extractShippingAddresses();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def extract_shipping_addresses():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.aggregate([
        {
            "$replaceRoot": {
                "newRoot": "$shippingAddress"
            }
        }
    ]))

    print(result)

    client.close()

extract_shipping_addresses()
```

------

# \$1replaceWith
<a name="replaceWith"></a>

New from version 8.0

Not supported by Elastic cluster.

The `$replaceWith` aggregation stage in Amazon DocumentDB is used to replace the input document with a new document. All existing fields on the input document, including the \$1id field, are replaced by the new document. `$replaceWith` is commonly used to flatten documents, or promote an embedded document to the top level.

**Parameters**
+ `<replacement>` (required): The new document that will replace the existing document.

## Example (MongoDB Shell)
<a name="replaceWith-examples"></a>

The following example demonstrates how to use the `$replaceWith` operator to replace an existing document in an Amazon DocumentDB collection.

**Create sample documents**

```
db.restaurants.insertMany([
  {
    "restaurantId": "REST-0Y9GL0",
    "name": "Biryani Adda",
    "cuisine": "Indian",
    "ratings": [ 3, 4, 3, 2, 2, 4, 1, 5, 5, 5 ]
  },
  {
    "restaurantId": "REST-8L2PX9",
    "name": "The Burger Spot",
    "cuisine": "American",
    "ratings": [ 2, 3, 4, 5, 3, 1, 1, 2, 4 ]
  }
]);
```

**Query example**

```
db.restaurants.aggregate([
  { $replaceWith: {
      name: "$name",
      cuisine: "$cuisine",
      rating: { $avg: "$ratings" }
    }
  }
]);
```

**Output**

```
[
  {
    name: 'Biryani Adda',
    cuisine: 'Indian',
    rating: 3.4
  },
  {
    name: 'The Burger Spot',
    cuisine: 'American',
    rating: 2.7777777777777777
  }
]
```

## Code examples
<a name="replaceWith-code"></a>

To view a code example for using the `$replaceWith` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function replaceDoc() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('restaurants');

  const result = await collection.aggregate([
    { $replaceWith: {
        name: "description_index",
        cuisine: 2,
        rating: { $avg: "$ratings" }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

replaceDoc();
```

------
#### [ Python ]

```
from pymongo import MongoClient


def replace_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.restaurants

    result = list(collection.aggregate([
        {
            '$replaceWith': {
                'name': "$name",
                'cuisine': "$cuisine",
                'rating': { '$avg': "$ratings"}
            }
        }
    ]))

    print(result)
    client.close()

replace_document()
```

------

# \$1reverseArray
<a name="reverseArray"></a>

The `$reverseArray` operator in Amazon DocumentDB is used to reverse the elements of an array in the specified order. This operator is useful when you need to reorder the elements of an array in the reverse direction.

**Parameters**
+ `expression`: The array expression to reverse.

## Example (MongoDB Shell)
<a name="reverseArray-examples"></a>

The following example demonstrates how to use the `$reverseArray` operator to reverse the order of elements in an array.

**Create sample documents**

```
db.miles.insertMany([
  { "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ]},
  { "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 2560, 890, 2780]},
  { "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 880]}
]);
```

**Query example**

```
db.miles.aggregate([
  {
    $project: {
      _id: 1,
      member_since: 1,
      credit_card: 1,
      reversed_flight_miles: { $reverseArray: "$flight_miles" }
    }
  }
]);
```

**Output**

```
{ "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "reversed_flight_miles" : [ 880, 2560, 1205 ] }
{ "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "reversed_flight_miles" : [ 2780, 890, 2560, 1205 ] }
{ "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "reversed_flight_miles" : [ 880, 1205 ] }
```

In this example, the `$reverseArray` operator is used to reverse the order of the `flight_miles` array. The resulting `reversed_flight_miles` field in the output shows the elements of the array in the reversed order.

## Code examples
<a name="reverseArray-code"></a>

To view a code example for using the `$reverseArray` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of using the `$reverseArray` operator in a Node.js application:

```
const { MongoClient } = require('mongodb');

async function reverseArray() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        member_since: 1,
        credit_card: 1,
        reversed_flight_miles: { $reverseArray: '$flight_miles' }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

reverseArray();
```

------
#### [ Python ]

Here's an example of using the `$reverseArray` operator in a Python application:

```
from pymongo import MongoClient

def reverse_array():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.miles

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'member_since': 1,
                'credit_card': 1,
                'reversed_flight_miles': { '$reverseArray': '$flight_miles' }
            }
        }
    ]))

    print(result)
    client.close()

reverse_array()
```

------

# \$1rtrim
<a name="rtrim"></a>

New from version 4.0.

Not supported by Elastic cluster.

The `$rtrim` operator in Amazon DocumentDB is used to remove trailing characters from a string. By default, it removes trailing whitespace characters, but you can also specify a set of characters to remove by passing the chars argument.

**Parameters**
+ `input`: The input string from which to remove trailing whitespace characters.
+ `chars`: (optional) To remove specific characters.

## Example (MongoDB Shell)
<a name="rtrim-examples"></a>

The following example demonstrates how to use the `$rtrim` operator to remove trailing specified characters (" \$1") from a string.

**Create sample documents**

```
db.collection.insert([
  { "name": "John Doe*  ", "age": 30 },
  { "name": "Jane Smith  ", "age": 25 },
  { "name": "Bob Johnson", "age": 35 }
]);
```

**Query example**

```
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      name: { $rtrim: { input: "$name", chars: " *" } }, 
      age: 1
    }
  }
]);
```

**Output**

```
[
  { age: 30, name: 'John Doe' },
  { age: 25, name: 'Jane Smith' },
  { age: 35, name: 'Bob Johnson' }
]
```

## Code examples
<a name="rtrim-code"></a>

To view a code example for using the `$rtrim` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient, Bson } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {

    const db = client.db('test');
    const collection = db.collection('collection');  

    const pipeline = [
      {
        $project: {
          _id: 0,
          name: { $rtrim: { input: "$name", chars: " *" } },
          age: 1
        }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();
    console.dir(results, { depth: null });

  } catch (err) {
    console.error('Error occurred:', err);
  } finally {
    await client.close();
  }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    try:

        db = client.test
        collection = db.collection

        pipeline = [
            {
                "$project": {
                    "_id": 0,
                    "name": { "$rtrim": { "input": "$name", "chars": " *" } },
                    "age": 1
                }
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        client.close()

example()
```

------

# \$1sample
<a name="sample"></a>

The `$sample` aggregation stage in Amazon DocumentDB is used to randomly select a specified number of documents from a collection. This is useful for tasks such as data analysis, testing, and generating samples for further processing.

**Parameters**
+ `size`: The number of documents to randomly select.

## Example (MongoDB Shell)
<a name="sample-examples"></a>

The following example demonstrates how to use the `$sample` stage to randomly select two documents from the `temp` collection.

**Create sample documents**

```
db.temp.insertMany([
  { "_id": 1, "temperature": 97.1, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 2, "temperature": 98.2, "humidity": 0.59, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 3, "temperature": 96.8, "humidity": 0.61, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 4, "temperature": 97.9, "humidity": 0.61, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 5, "temperature": 97.5, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 6, "temperature": 98.0, "humidity": 0.59, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 7, "temperature": 97.2, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 8, "temperature": 98.1, "humidity": 0.59, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 9, "temperature": 96.9, "humidity": 0.62, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 10, "temperature": 97.7, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }
]);
```

**Query example**

```
db.temp.aggregate([
   { $sample: { size: 2 } }
])
```

**Output**

```
{ "_id" : 4, "temperature" : 97.9, "humidity" : 0.61, "timestamp" : ISODate("2019-03-21T21:17:22.425Z") }
{ "_id" : 9, "temperature" : 96.9, "humidity" : 0.62, "timestamp" : ISODate("2019-03-21T21:17:22.425Z") }
```

As the results show, 2 of the 10 documents were randomly sampled. You can now use these documents to determine an average or to perform min/max calculations.

## Code examples
<a name="sample-code"></a>

To view a code example for using the `$sample` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function sampleDocuments() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('temp');

  const result = await collection.aggregate([
    { $sample: { size: 2 } }
  ]).toArray();

  console.log(result);
  await client.close();
}

sampleDocuments();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def sample_documents():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['temp']

    result = list(collection.aggregate([
        { '$sample': { 'size': 2 } }
    ]))

    print(result)
    client.close()

sample_documents()
```

------

# \$1search
<a name="search"></a>

New from version 5.0.

The `$search` operator in Amazon DocumentDB is used to provide text search capabilities.

**Parameters**

None

## Example (MongoDB Shell)
<a name="search-examples"></a>

The following example demonstrates how to use the `$search` operator to perform a text search query.

**Create sample documents**

```
db.textcollection.createIndex({"description": "text"});

db.textcollection.insertMany([
  { _id: 1, name: "John Doe", description: "This is a sample document about John Doe." },
  { _id: 2, name: "Jane Smith", description: "This is a sample document about Jane Smith." },
  { _id: 3, name: "Bob Johnson", description: "This is a sample document about Bob Johnson." },
  { _id: 4, name: "Jon Jeffries", description: "This is a sample document about Jon Jeffries." }
]);
```

**Query example**

```
db.textcollection.find(
  { $text: { $search: "John" } }
);
```

**Output**

```
[
  {
    _id: 1,
    name: 'John Doe',
    description: 'This is a sample document about John Doe.'
  }
]
```

## Code examples
<a name="search-code"></a>

To view a code example for using the `$search` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findWithText() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('textcollection');

  const result = await collection.find(
    { $text: { $search: "John" } }
  ).sort({ score: { $meta: "textScore" } }).toArray();

  console.log(result);
  client.close();
}

findWithText();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_with_text():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['textcollection']

    result = list(collection.find(
        { '$text': { '$search': 'John' } }
    ))

    print(result)
    client.close()

find_with_text()
```

------

# \$1second
<a name="second"></a>

The `$second` operator in Amazon DocumentDB extracts the seconds component from a date or timestamp. It is used to retrieve the seconds value from a date or timestamp field.

**Parameters**
+ `expression`: The date or timestamp field to extract the seconds value from. This expression can be a field path or any valid expression that resolves to a date or timestamp.

## Example (MongoDB Shell)
<a name="second-examples"></a>

The following example demonstrates how to use the `$second` operator to extract the seconds component from a date field.

**Create sample documents**

```
db.users.insertMany([
  { name: "John", dob: new Date("1990-05-15T12:30:45Z") },
  { name: "Jane", dob: new Date("1985-09-20T23:59:59Z") },
  { name: "Bob", dob: new Date("2000-01-01T00:00:00Z") }
]);
```

**Query example**

```
db.users.aggregate([{ $project: { name: 1, dobSeconds: { $second: "$dob" } } }])
```

**Output**

```
[
  { "_id" : ObjectId("6089a9c306a829d1f8b456a1"), "name" : "John", "dobSeconds" : 45 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a2"), "name" : "Jane", "dobSeconds" : 59 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a3"), "name" : "Bob", "dobSeconds" : 0 }
]
```

## Code examples
<a name="second-code"></a>

To view a code example for using the `$second` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([{ $project: { name: 1, dobSeconds: { $second: '$dob' } } }]).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = list(users.aggregate([{'$project': {'name': 1, 'dobSeconds': {'$second': '$dob'}}}]))
    print(result)

    client.close()

example ()
```

------

# \$1set
<a name="set-stage"></a>

New from version 8.0

Not supported by Elastic cluster.

The `$set` aggregation stage in Amazon DocumentDB allows you to add new fields or update existing field values in documentation during an aggregation pipeline.

**Parameters**
+ `expression`: The expression to evaluate. This can be any valid aggregation expression, including field references and arithmetic operations.

## Example (MongoDB Shell)
<a name="set-stage-examples"></a>

The following example demonstrates the use of the `$set` aggregation stage to calculate totals by multiplying the `quantity` field by the `price` field.

**Create sample documents**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**Aggregation example**

```
db.inventory.aggregate([
  {
    $set: {
      total: { $multiply: ["$quantity", "$price"] }
    }
  }
])
```

**Output**

```
[
  {
    _id: ObjectId('69248951d66dcae121d2950d'),
    item: 'pencil',
    quantity: 100,
    price: 0.24,
    total: 24
  },
  {
    _id: ObjectId('69248951d66dcae121d2950e'),
    item: 'pen',
    quantity: 204,
    price: 1.78,
    total: 363.12
  }
]
```

## Code examples
<a name="set-stage-code"></a>

To view a code example for using the `$set` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const inventory = db.collection('inventory');

  const result = await inventory.aggregate([
      {
        $set: {
          total: { $multiply: ["$quantity", "$price"] }
        }
      }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    inventory = db['inventory']

    result = list(inventory.aggregate([
      {
        "$set": {
          "total": { "$multiply": ["$quantity", "$price"] }
        }
      }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1setDifference
<a name="setDifference"></a>

New from version 4.0.

The `$setDifference` operator in Amazon DocumentDB is used to compare two sets and return the elements that are in the first set but not in the second set. This operator is useful for finding the unique elements between two sets.

**Parameters**
+ `firstSet` : The first set to compare.
+ `secondSet` : The second set to compare.

## Example (MongoDB Shell)
<a name="setDifference-examples"></a>

The following example demonstrates how to use the `$setDifference` operator to find the unique elements between two sets.

**Create sample documents**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry", "date"] },
  { _id: 2, fruits: ["banana", "cherry", "date", "elderberry"] }
]);
```

**Query example**

```
db.collection.aggregate([
  {
    $project: {
      uniqueFruits: { $setDifference: ["$fruits", ["banana", "cherry", "date"]] }
    }
  }
]);
```

**Output**

```
[
  { "_id": 1, "uniqueFruits": ["apple"] },
  { "_id": 2, "uniqueFruits": ["elderberry"] }
]
```

The query performs the following steps:

1. It uses the `$project` stage to create a new field `uniqueFruits` for each document.

2. The `$setDifference` operator compares the `fruits` array with the array `[&quot;banana&quot;, &quot;cherry&quot;, &quot;date&quot;]` and returns the unique elements in the `fruits` array.

## Code examples
<a name="setDifference-code"></a>

To view a code example for using the `$setDifference` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of how to use the `$setDifference` operator in a Node.js application:

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('mycollection');

  // Insert sample documents
  await collection.insertMany([
    { _id: 1, fruits: ["apple", "banana", "cherry", "date"] },
    { _id: 2, fruits: ["banana", "cherry", "date", "elderberry"] }
  ]);

 // Query using $setDifference
  const result = await collection.aggregate([
    {
      $project: {
        uniqueFruits: { $setDifference: ["$fruits", ["banana", "cherry", "date"]] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

Here's an example of how to use the `$setDifference` operator in a Python application:

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['mycollection']

    # Insert sample documents
    collection.insert_many([
        {'_id': 1, 'fruits': ["apple", "banana", "cherry", "date"]},
        {'_id': 2, 'fruits': ["banana", "cherry", "date", "elderberry"]}
    ])

    # Query using $setDifference
    result = list(collection.aggregate([
        {
            '$project': {
                'uniqueFruits': {'$setDifference': ['$fruits', ["banana", "cherry", "date"]]}
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1setEquals
<a name="setEquals"></a>

The `$setEquals` operator in Amazon DocumentDB is used to determine if two sets are equal. It compares two arrays and returns `true` if they contain the same distinct elements, regardless of their order.

**Parameters**
+ `expression1`: The first array to compare.
+ `expression2`: The second array to compare.

## Example (MongoDB Shell)
<a name="setEquals-examples"></a>

The following example demonstrates the usage of the `$setEquals` operator to compare two sets of values.

**Create sample documents**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry"] },
  { _id: 2, fruits: ["banana", "apple", "cherry"] },
  { _id: 3, fruits: ["apple", "banana", "orange"] }
])
```

**Query example**

```
db.collection.find({
  $expr: {
    $setEquals: ["$fruits", ["apple", "banana", "cherry"]]
  }
})
```

**Output**

```
{ "_id" : 1, "fruits" : [ "apple", "banana", "cherry" ] }
{ "_id" : 2, "fruits" : [ "banana", "apple", "cherry" ] }
```

The query uses the `$setEquals` operator to compare the `fruits` field of each document with the array `[&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]`. The documents where the `fruits` field is equal to the comparison array are returned.

## Code examples
<a name="setEquals-code"></a>

To view a code example for using the `$setEquals` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('mycollection');

  // Insert sample documents
  await collection.insertMany([
    { _id: 1, fruits: ["apple", "banana", "cherry"] },
    { _id: 2, fruits: ["banana", "apple", "cherry"] },
    { _id: 3, fruits: ["apple", "banana", "orange"] }
  ]);

  // Query using $setEquals
  const result = await collection.find({
    $expr: {
      $setEquals: ["$fruits", ["apple", "banana", "cherry"]]
    }
  }).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['mycollection']

    # Insert sample documents
    collection.insert_many([
        {"_id": 1, "fruits": ["apple", "banana", "cherry"]},
        {"_id": 2, "fruits": ["banana", "apple", "cherry"]},
        {"_id": 3, "fruits": ["apple", "banana", "orange"]}
    ])

    # Query using $setEquals
    result = list(collection.find({
        "$expr": {
            "$setEquals": ["$fruits", ["apple", "banana", "cherry"]]
        }
    }))

    print(result)
    client.close()

example()
```

------

# \$1setIntersection
<a name="setIntersection"></a>

The `$setIntersection` operator in Amazon DocumentDB is used to return the common elements between two or more arrays. This operator is particularly useful when working with sets of data, allowing you to find the intersection of multiple sets.

**Parameters**
+ `array1`: The first array to intersect.
+ `array2`: The second array to intersect.
+ `arrayN`: (optional) Additional arrays to intersect.

## Example (MongoDB Shell)
<a name="setIntersection-examples"></a>

The following example demonstrates how to use the `$setIntersection` operator to find the common elements between two arrays.

**Create sample documents**

```
db.collection.insertMany([
  { _id: 1, colors: ["red", "blue", "green"] },
  { _id: 2, colors: ["blue", "yellow", "orange"] },
  { _id: 3, colors: ["red", "green", "purple"] }
])
```

**Query example**

```
db.collection.aggregate([
  { $project: {
      _id: 1,
      commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
    }
  }
])
```

**Output**

```
[
  { "_id": 1, "commonColors": ["red", "blue", "green"] },
  { "_id": 2, "commonColors": ["blue"] },
  { "_id": 3, "commonColors": ["red", "green"] }
]
```

## Code examples
<a name="setIntersection-code"></a>

To view a code example for using the `$setIntersection` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('mycollection');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['mycollection']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'commonColors': { '$setIntersection': ["$colors", ["red", "blue", "green"]] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1setIsSubset
<a name="setIsSubset"></a>

The `$setIsSubset` operator in Amazon DocumentDB is used to determine if a set of values is a subset of another set. It is useful for performing set-based comparisons and operations on array fields.

**Parameters**
+ `field`: The field to apply the `$setIsSubset` operator to.
+ `set`: The set to compare the field against.

## Example (MongoDB Shell)
<a name="setIsSubset-examples"></a>

The following example demonstrates the usage of the `$setIsSubset` operator to check if the `tags` field is a subset of the specified set.

**Create sample documents**

```
db.products.insertMany([
  { _id: 1, name: "Product A", tags: ["tag1", "tag2", "tag3"] },
  { _id: 2, name: "Product B", tags: ["tag1", "tag2"] },
  { _id: 3, name: "Product C", tags: ["tag2", "tag3"] }
]);
```

**Query example**

```
db.products.find({
  $expr: { $setIsSubset: [["tag1", "tag2"], "$tags"] }
})
```

\$1Note:\$1 `$setIsSubset` is an aggregation operator and cannot be used directly in find() queries. In this example, `$expr` is used with `find()` to bridge the gap between query operators and aggregation expressions.

**Output**

```
[
  { "_id" : 1, "name" : "Product A", "tags" : [ "tag1", "tag2", "tag3" ] },
  { "_id" : 2, "name" : "Product B", "tags" : [ "tag1", "tag2" ] }
]
```

The query returns the documents where the `tags` field is a subset of the set `[&quot;tag1&quot;, &quot;tag2&quot;]`.

## Code examples
<a name="setIsSubset-code"></a>

To view a code example for using the `$setIsSubset` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.find({
    $expr: { $setIsSubset: [["tag1", "tag2"], "$tags"] }
  }).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.find({
        '$expr': {'$setIsSubset': [['tag1', 'tag2'], '$tags']}
    }))

    print(result)

    client.close()

example()
```

------

# \$1setUnion
<a name="setUnion"></a>

The `$setUnion` aggregation operator in Amazon DocumentDB is used to combine two or more sets of values and return a set that contains all the unique elements from the input sets. This operator is useful when you need to perform set-based operations on array fields in your documents.

**Parameters**
+ `expression1`: An expression that resolves to an array.
+ `expression2`: An expression that resolves to an array.
+ `expressionN`: Additional expressions that resolve to arrays (optional).

## Example (MongoDB Shell)
<a name="setUnion-examples"></a>

The following example demonstrates how to use the `$setUnion` operator to combine the unique elements from two array fields in a collection.

**Create sample documents**

```
db.users.insertMany([
  { _id: 1, name: "Alice", hobbies: ["reading", "swimming"], skills: ["coding", "writing"] },
  { _id: 2, name: "Bob", hobbies: ["cooking", "gardening"], skills: ["coding", "photography"] },
  { _id: 3, name: "Charlie", hobbies: ["reading", "painting"], skills: ["gardening", "music"] }
]);
```

**Query example**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      allInterests: { $setUnion: ["$hobbies", "$skills"] }
    }
  }
]);
```

**Output**

```
[
  { "_id" : 1, "name" : "Alice", "allInterests" : [ "coding", "reading", "swimming", "writing" ] },
  { "_id" : 2, "name" : "Bob", "allInterests" : [ "coding", "cooking", "gardening", "photography" ] },
  { "_id" : 3, "name" : "Charlie", "allInterests" : [ "gardening", "music", "painting", "reading" ] }
]
```

In this example, the `$setUnion` operator is used to combine the unique elements from the `hobbies` and `skills` array fields for each user document. The resulting `allInterests` field contains the union of all the unique hobbies and skills for each user.

## Code examples
<a name="setUnion-code"></a>

To view a code example for using the `$setUnion` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([
    {
      $project: {
        _id: 1,
        name: 1,
        allInterests: { $setUnion: ["$hobbies", "$skills"] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = list(users.aggregate([
        {
            '$project': {
                '_id': 1,
                'name': 1,
                'allInterests': { '$setUnion': ["$hobbies", "$skills"] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1skip
<a name="skip"></a>

In Amazon DocumentDB, the `$skip` operator is used to offset the starting point of the query results, allowing you to retrieve a specific subset of the matching documents. This is particularly useful in pagination scenarios, where you want to retrieve subsequent pages of results.

**Parameters**
+ `skip`: The number of documents to skip before returning the remaining documents.

## Example (MongoDB Shell)
<a name="skip-examples"></a>

The following example demonstrates how to use the `$skip` operator to retrieve the second page of results (documents 11-20) from a collection.

**Create sample documents**

```
db.collection.insert([
  { "name": "Document 1" },
  { "name": "Document 2" },
  { "name": "Document 3" },
  { "name": "Document 4" },
  { "name": "Document 5" },
  { "name": "Document 6" },
  { "name": "Document 7" },
  { "name": "Document 8" },
  { "name": "Document 9" },
  { "name": "Document 10" },
  { "name": "Document 11" },
  { "name": "Document 12" },
  { "name": "Document 13" },
  { "name": "Document 14" },
  { "name": "Document 15" },
  { "name": "Document 16" },
  { "name": "Document 17" },
  { "name": "Document 18" },
  { "name": "Document 19" },
  { "name": "Document 20" }
]);
```

**Query example**

```
db.collection.find({}, { "name": 1 })
             .skip(10)
             .limit(10);
```

**Output**

```
[
  { "_id" : ObjectId("..."), "name" : "Document 11" },
  { "_id" : ObjectId("..."), "name" : "Document 12" },
  { "_id" : ObjectId("..."), "name" : "Document 13" },
  { "_id" : ObjectId("..."), "name" : "Document 14" },
  { "_id" : ObjectId("..."), "name" : "Document 15" },
  { "_id" : ObjectId("..."), "name" : "Document 16" },
  { "_id" : ObjectId("..."), "name" : "Document 17" },
  { "_id" : ObjectId("..."), "name" : "Document 18" },
  { "_id" : ObjectId("..."), "name" : "Document 19" },
  { "_id" : ObjectId("..."), "name" : "Document 20" }
]
```

## Code examples
<a name="skip-code"></a>

To view a code example for using the `$skip` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const results = await collection.find({}, { projection: { name: 1 } })
                                 .skip(10)
                                 .limit(10)
                                 .toArray();

  console.log(results);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.mydatabase
    collection = db.collection

    results = list(collection.find({}, {'name': 1})
                   .skip(10)
                   .limit(10))

    print(results)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1slice
<a name="slice"></a>

The `$slice` aggregation operator enables you to return a subset of an array by either traversing the array from the beginning or the end of the array. This is used to display a limited number of items from an array field, such as the top or bottom N items.

**Parameters**
+ `array`: The array field to be sliced.
+ `n`: An integer that specifies the number of elements to return. A positive value starts from the beginning of the array, while a negative value starts from the end of the array.

## Example (MongoDB Shell)
<a name="slice-examples"></a>

The following example demonstrates how to use `$slice` to return the first two favorite sweets for each chef.

**Create sample documents**

```
db.sweets.insertMany([
  { "_id" : 1, "name" : "Alvin", "favorites": [ "chocolate", "cake", "toffee", "beignets" ] },
  { "_id" : 2, "name" : "Tom", "favorites": [ "donuts", "pudding", "pie" ] },
  { "_id" : 3, "name" : "Jessica", "favorites": [ "fudge", "smores", "pudding", "cupcakes" ] },
  { "_id" : 4, "name" : "Rachel", "favorites": [ "ice cream" ] }
]);
```

**Query example**

```
db.sweets.aggregate([
  { $project: { _id: 0, name: 1, topTwoFavorites: { $slice: [ "$favorites", 2 ] } } }
]);
```

**Output**

```
[
  { name: 'Alvin', topTwoFavorites: [ 'chocolate', 'cake' ] },
  { name: 'Tom', topTwoFavorites: [ 'donuts', 'pudding' ] },
  { name: 'Jessica', topTwoFavorites: [ 'fudge', 'smores' ] },
  { name: 'Rachel', topTwoFavorites: [ 'ice cream' ] }
]
```

In this example, the `$slice` operator is used to extract the first two elements from the `favorites` array for each document.

## Code examples
<a name="slice-code"></a>

To view a code example for using the `$slice` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('sweets');

  const result = await collection.aggregate([
    { $project: { name: 1, topTwoFavorites: { $slice: ['$favorites', 2] } } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['sweets']

    result = list(collection.aggregate([
        { '$project': { 'name': 1, 'topTwoFavorites': { '$slice': ['$favorites', 2] } } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1size
<a name="size"></a>

The `$size` operator is used to return the count of items within an array field. This can be used to determine the number of elements in an array stored in a document.

**Parameters**
+ `field`: The field path whose array size you want to return.

## Example (MongoDB Shell)
<a name="size-examples"></a>

This example shows how to use the `$size` operator to return the count of teams each user is following.

**Create sample documents**

```
db.profiles.insertMany([
  { _id: 1, name: "John Doe", teams: ["Acme", "Widgets", "Gadgets"] },
  { _id: 2, name: "Jane Smith", teams: ["Acme", "Gadgets"] },
  { _id: 3, name: "Bob Johnson", teams: ["Acme", "Widgets", "Gadgets"] }
]);
```

**Query example**

```
db.profiles.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      "numberOfTeams": { $size: "$teams" }
    }
  }
])
```

**Output**

```
[
  { name: 'John Doe', numberOfTeams: 3 },
  { name: 'Jane Smith', numberOfTeams: 2 },
  { name: 'Bob Johnson', numberOfTeams: 3 }
]
```

## Code examples
<a name="size-code"></a>

To view a code example for using the `$size` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const profiles = db.collection('profiles');

  const result = await profiles.aggregate([
    {
      $project: {
        item: 1,
        "numberOfTeams": { $size: "$teams" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    profiles = db.profiles

    result = list(profiles.aggregate([
        {
            '$project': {
                'item': 1,
                'numberOfTeams': { '$size': '$teams' }
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1sort
<a name="sort"></a>

The `$sort` aggregation stage orders documents in the pipeline based on specified field values. Documents are arranged in ascending or descending order according to the sort criteria provided.

**Parameters**
+ `field`: The field name to sort by.
+ `order`: Use `1` for ascending order or `-1` for descending order.

## Example (MongoDB Shell)
<a name="sort-examples"></a>

The following example demonstrates using the `$sort` stage to order products by price in descending order.

**Create sample documents**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", category: "Electronics", price: 1200 },
  { _id: 2, name: "Mouse", category: "Electronics", price: 25 },
  { _id: 3, name: "Desk", category: "Furniture", price: 350 },
  { _id: 4, name: "Chair", category: "Furniture", price: 150 },
  { _id: 5, name: "Monitor", category: "Electronics", price: 400 }
]);
```

**Query example**

```
db.products.aggregate([
  { $sort: { price: -1 } }
]);
```

**Output**

```
[
  { _id: 1, name: 'Laptop', category: 'Electronics', price: 1200 },
  { _id: 5, name: 'Monitor', category: 'Electronics', price: 400 },
  { _id: 3, name: 'Desk', category: 'Furniture', price: 350 },
  { _id: 4, name: 'Chair', category: 'Furniture', price: 150 },
  { _id: 2, name: 'Mouse', category: 'Electronics', price: 25 }
]
```

## Code examples
<a name="sort-code"></a>

To view a code example for using the `$sort` aggregation stage, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.aggregate([
    { $sort: { price: -1 } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.aggregate([
        { '$sort': { 'price': -1 } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1split
<a name="split"></a>

The `$split` aggregation operator in Amazon DocumentDB is used to split a string into an array of substrings, based on a specified delimiter. This can be useful for parsing complex string fields and extracting individual components for further processing.

**Parameters**
+ `string`: The string to be split.
+ `delimiter`: The character or string used to split the input string.

## Example (MongoDB Shell)
<a name="split-examples"></a>

In this example, we use `$split` to separate the components of a "Desk" field into an array, making it easier to process the data.

**Create sample documents**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
```

**Query example**

```
db.people.aggregate([
  { $project: { parts: { $split: ["$Desk", "-"] } } }
]);
```

**Output**

```
{ "_id" : 1, "parts" : [ "Düsseldorf", "BVV", "021" ] }
{ "_id" : 2, "parts" : [ "Munich", "HGG", "32a" ] }
{ "_id" : 3, "parts" : [ "Cologne", "ayu", "892.50" ] }
{ "_id" : 4, "parts" : [ "Dortmund", "Hop", "78" ] }
```

The output of `$split` creates an array that can be used in the application to display the information for the employees.

## Code examples
<a name="split-code"></a>

To view a code example for using the `$split` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const result = await db.collection('people').aggregate([
    { $project: { parts: { $split: ['$Desk', '-'] } } }
  ]).toArray();
  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    result = list(db.people.aggregate([
        { '$project': { 'parts': { '$split': ['$Desk', '-'] } } }
    ]))
    print(result)
    client.close()

example()
```

------

# \$1sqrt
<a name="sqrt"></a>

New from version 4.0.

The `$sqrt` operator in Amazon DocumentDB is used to calculate the square root of a number.

**Parameters**
+ `expression`: The argument can be any valid expression as long as it resolves to a non-negative number.

## Example (MongoDB Shell)
<a name="sqrt-examples"></a>

The following example demonstrates the usage of the `$sqrt` operator to calculate the square root of a number.

**Create sample documents**

```
db.numbers.insertMany([
  { "_id": 1, "number": 16 },
  { "_id": 2, "number": 36 },
  { "_id": 3, "number": 64 }
]);
```

**Query example**

```
db.numbers.aggregate([
  { $project: {
    "_id": 1,
    "square_root": { $sqrt: "$number" }
  }}
]);
```

**Output**

```
[
  { _id: 1, square_root: 4 },
  { _id: 2, square_root: 6 },
  { _id: 3, square_root: 8 }
]
```

## Code examples
<a name="sqrt-code"></a>

To view a code example for using the `$sqrt` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
      await client.connect();

      const db = client.db('test');
      const collection = db.collection('numbers');

      const pipeline = [
        {
          $project: {
            _id: 1,
            square_root: { $sqrt: '$number' }
          }
        }
      ];

      const results = await collection.aggregate(pipeline).toArray();

      console.dir(results, { depth: null });

    } finally {
      await client.close();
    }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
  
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

  try:
      db = client.test
      collection = db.numbers

      pipeline = [
          {
              "$project": {
                  "_id": 1,
                  "square_root": { 
                    "$sqrt": "$number" 
                  }
              }
          }
      ]

      results = collection.aggregate(pipeline)

      for doc in results:
          print(doc)

  except Exception as e:
      print(f"An error occurred: {e}")

  finally:
      client.close()

example()
```

------

# \$1strLenBytes
<a name="strLenBytes"></a>

The `$strLenBytes` operator in Amazon DocumentDB is used to determine the length of a string in bytes. This is useful when you need to understand the storage size of a string field, especially when dealing with Unicode characters that may use more than one byte per character.

**Parameters**
+ `expression`: The string expression to calculate the length of.

## Example (MongoDB Shell)
<a name="strLenBytes-examples"></a>

This example demonstrates how to use the `$strLenBytes` operator to calculate the length of string fields in bytes.

**Create sample documents**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
```

**Query example**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenBytes: "$Desk" }
    }
  }
])
```

**Output**

```
{ "_id" : 1, "Desk" : "Düsseldorf-BVV-021", "length" : 19 }
{ "_id" : 2, "Desk" : "Munich-HGG-32a", "length" : 14 }
{ "_id" : 3, "Desk" : "Cologne-ayu-892.50", "length" : 18 }
{ "_id" : 4, "Desk" : "Dortmund-Hop-78", "length" : 15 }
```

Note that the length of the "Düsseldorf-BVV-021" string is 19 bytes, which is different from the number of code points (18) due to the Unicode character "Ü" occupying 2 bytes.

## Code examples
<a name="strLenBytes-code"></a>

To view a code example for using the `$strLenBytes` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    {
      $project: {
        "Desk": 1,
        "length": { $strLenBytes: "$Desk" }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                "Desk": 1,
                "length": { "$strLenBytes": "$Desk" }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1strLenCP
<a name="strLenCP"></a>

The `$strLenCP` operator in Amazon DocumentDB is used to determine the length of a string expression in code points (Unicode characters). This is useful when you need to know the number of characters in a string, rather than the number of bytes.

**Parameters**
+ `expression`: The string expression for which to return the length in code points.

## Example (MongoDB Shell)
<a name="strLenCP-examples"></a>

The following example demonstrates the usage of the `$strLenCP` operator to determine the length of strings with Unicode characters.

**Create sample documents**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
])
```

**Query example**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenCP: "$Desk" }
    }
  }
])
```

**Output**

```
{ "_id" : 1, "Desk" : "Düsseldorf-BVV-021", "length" : 18 }
{ "_id" : 2, "Desk" : "Munich-HGG-32a", "length" : 14 }
{ "_id" : 3, "Desk" : "Cologne-ayu-892.50", "length" : 18 }
{ "_id" : 4, "Desk" : "Dortmund-Hop-78", "length" : 15 }
```

Notice the difference in the length measurement for the "Düsseldorf-BVV-021" string, which contains a Unicode character (Ü). The `$strLenCP` operator correctly counts the number of Unicode characters, while the `$strLenBytes` operator counts the number of bytes.

## Code examples
<a name="strLenCP-code"></a>

To view a code example for using the `$strLenCP` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

Here's an example of using the `$strLenCP` operator in a Node.js application with the MongoDB driver:

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    {
      $project: {
        "Desk": 1,
        "length": { $strLenCP: "$Desk" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

Here's an example of using the `$strLenCP` operator in a Python application with the PyMongo driver:

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                "Desk": 1,
                "length": { "$strLenCP": "$Desk" }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1strcasecmp
<a name="strcasecmp"></a>

The `$strcasecmp` operator in Amazon DocumentDB performs a case-insensitive comparison between two strings. It returns an integer value indicating the lexicographic comparison of the two input strings, ignoring case differences.

**Parameters**
+ `string1`: The first string to compare.
+ `string2`: The second string to compare.

## Example (MongoDB Shell)
<a name="strcasecmp-examples"></a>

This example demonstrates how to use the `$strcasecmp` operator to compare desk location strings in a `people` collection, ignoring case differences.

**Create sample documents**

```
db.people.insertMany([
  { "_id": 1, "Desk": "mke233-wi" },
  { "_id": 2, "Desk": "MKE233-WI" },
  { "_id": 3, "Desk": "mke233-wi" }
]);
```

**Query example**

```
db.people.aggregate([
  {
    $project: {
      item: 1,
      compare: { $strcasecmp: ["$Desk", "mke233-wi"] }
    }
  }
]);
```

**Output**

```
{ "_id" : 1, "compare" : 0 }
{ "_id" : 2, "compare" : 0 }
{ "_id" : 3, "compare" : 0 }
```

The output shows that the comparison between the `&quot;Desk&quot;` field and the string `&quot;mke233-wi&quot;` returns `0` for all three documents, indicating that the strings are equal when case is ignored.

## Code examples
<a name="strcasecmp-code"></a>

To view a code example for using the `$strcasecmp` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        compare: { $strcasecmp: ["$Desk", "mke233-wi"] }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'compare': { '$strcasecmp': ['$Desk', 'mke233-wi'] }
            }
        }
    ]))

    print(result)

    client.close()

example()
```

------

# \$1substr
<a name="substr"></a>

The `$substr` operator in Amazon DocumentDB is used to extract a substring from a given string. It is particularly useful when you need to define substrings based on a range of characters, rather than a range of bytes. This is especially important when dealing with Unicode strings, where the number of bytes used to represent a character can vary.

**Parameters**
+ `string`: The input string from which to extract the substring.
+ `start`: The starting position (zero-based) of the substring to be extracted. Can be a non-negative integer expression.
+ `length`: The number of characters in the extracted substring. Can be a non-negative integer expression.

## Example (MongoDB Shell)
<a name="substr-examples"></a>

In this example, we'll demonstrate the use of `$substr` to extract the state abbreviation from an employee's desk location.

**Create sample documents**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-NRW-021" },
  { "_id": 2, "Desk": "Bremerhaven-HBB-32a" },
  { "_id": 3, "Desk": "Norderstedt-SHH-892.50" },
  { "_id": 4, "Desk": "Brandenburg-BBB-78" }
]);
```

**Query example**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substr: ["$Desk", 12, 3] }
    }
  }
])
```

**Output**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

## Code examples
<a name="substr-code"></a>

To view a code example for using the `$substr` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function example() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const collection = db.collection("people");

  const result = await collection.aggregate([
    {
      $project: {
        "state": { $substrCP: ["$Desk", 12, 3] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    collection = db["people"]

    result = list(collection.aggregate([
        {
            "$project": {
                "state": { "$substrCP": ["$Desk", 12, 3] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1substrBytes
<a name="substrBytes"></a>

The `$substrBytes` operator in Amazon DocumentDB is used to extract a substring from a string based on a specified byte range. This operator is useful when you need to extract a substring from a string and the number of bytes required to represent each character in the string is important.

Unlike `$substrCP`, which operates on the number of Unicode code points, `$substrBytes` operates on the number of bytes required to represent the characters in the string. This can be particularly useful when working with strings that contain non-ASCII characters, as these characters may require more than one byte to represent.

\$1Note:\$1 `$substr` has been deprecated since version 3.4. `$substr` is now an alias for `$substrBytes`.

**Parameters**
+ `string`: The input string from which the substring will be extracted.
+ `startByte`: The zero-based starting byte position of the substring to be extracted. A negative value can be used to specify a position from the end of the string.
+ `length`: The number of bytes in the substring to be extracted.

## Example (MongoDB Shell)
<a name="substrBytes-examples"></a>

In this example, we'll use `$substrBytes` to extract a substring from a string that contains non-ASCII characters.

**Create sample documents**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-NRW-021" },
  { "_id": 2, "Desk": "Bremerhaven-HBB-32a" },
  { "_id": 3, "Desk": "Norderstedt-SHH-892.50" },
  { "_id": 4, "Desk": "Brandenburg-BBB-78" }
]);
```

**Query example**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrBytes: [ "$Desk", 12, 3] }
    }
  }
])
```

**Output**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

In this example, we use `$substrBytes` to extract a 3-byte substring starting from the 12th byte of the `Desk` field. This allows us to extract the 2-character state abbreviation, even though the string may contain non-ASCII characters.

## Code examples
<a name="substrBytes-code"></a>

To view a code example for using the `$substrBytes` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const people = db.collection('people');

  const result = await people.aggregate([
    {
      $project: {
        "state": { $substrBytes: ["$Desk", 12, 3] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    people = db.people

    result = list(people.aggregate([
        {
            '$project': {
                "state": { '$substrBytes': ["$Desk", 12, 3] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1substrCP
<a name="substrCP"></a>

The `$substrCP` operator in Amazon DocumentDB is used to extract a substring from a string, where the substring is specified as a range of UTF-8 code points (CP). This operator is particularly useful when working with Unicode strings, as it allows you to extract substrings without having to worry about the underlying byte representation of the characters.

Unlike the `$substrBytes` operator, which operates on byte positions, the `$substrCP` operator works with code point positions. This makes it easier to work with strings that contain non-ASCII characters, as the number of code points may not match the number of bytes or characters.

**Parameters**
+ `string`: The input string from which to extract the substring.
+ `start`: The starting code point position (zero-based) from which to extract the substring.
+ `length`: The number of code points to extract.

## Example (MongoDB Shell)
<a name="substrCP-examples"></a>

In this example, we'll use the `$substrCP` operator to extract the state abbreviation from a string containing the employee's desk location.

**Create sample documents**

```
db.people.insert([
  { "_id": 1, "first_name": "Jane", "last_name": "Doe", "Desk": "12 Main St, Minneapolis, MN 55401" },
  { "_id": 2, "first_name": "John", "last_name": "Doe", "Desk": "456 Oak Rd, New Orleans, LA 70032" },
  { "_id": 3, "first_name": "Steve", "last_name": "Smith", "Desk": "789 Elm Ln, Bakersfield, CA 93263" }
]);
```

**Query example**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrCP: ["$Desk", 25, 2] }
    }
  }
]);
```

**Output**

```
{ "_id" : 1, "state" : "MN" }
{ "_id" : 2, "state" : "LA" }
{ "_id" : 3, "state" : "CA" }
```

In this example, we know that the state abbreviation starts at the 25th code point in the `Desk` field and is 2 code points long. By using the `$substrCP` operator, we can extract the state abbreviation without having to worry about the underlying byte representation of the string.

## Code examples
<a name="substrCP-code"></a>

To view a code example for using the `$substrCP` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findStates() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const result = await db.collection('people').aggregate([
    {
      $project: {
        "state": { $substrCP: ["$Desk", 25, 2] }
      }
    }
  ]).toArray();
  console.log(result);
  client.close();
}

findStates();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_states():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    result = list(db.people.aggregate([
        {
            '$project': {
                'state': { '$substrCP': ['$Desk', 25, 2] }
            }
        }
    ]))
    print(result)
    client.close()

find_states()
```

In both the Node.js and Python examples, we use the `$substrCP` operator to extract the state abbreviation from the `Desk` field, similar to the MongoDB Shell example.

------

# \$1subtract
<a name="subtract"></a>

The `$subtract` operator in Amazon DocumentDB is used to subtract values. It can be used to subtract dates, numbers, or a combination of both. This operator is useful for calculating the difference between two dates or subtracting a value from a number.

**Parameters**
+ `expression1`: The first value to be subtracted.
+ `expression2`: The second value to be subtracted from `<expression1>`.

## Example (MongoDB Shell)
<a name="subtract-examples"></a>

The following example demonstrates how to use the `$subtract` operator to calculate the difference between two dates.

**Create sample document**

```
db.dates.insert([
  {
  "_id": 1,
  "startDate": ISODate("2023-01-01T00:00:00Z"),
  "endDate": ISODate("2023-01-05T12:00:00Z")
  }
]);
```

**Query example**

```
db.dates.aggregate([
  {
    $project: {
      _id: 1,
      durationDays: {
        $divide: [
          { $subtract: ["$endDate", "$startDate"] },
          1000 * 60 * 60 * 24  // milliseconds in a day
        ]
      }
    }
  }
]);
```

**Output**

```
[ { _id: 1, durationDays: 4.5 } ]
```

In this example, the `$subtract` operator is used to calculate the difference between the `$endDate` and `$startDate` in days.

## Code examples
<a name="subtract-code"></a>

To view a code example for using the `$subtract` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();
    const db = client.db('test');
    const collection = db.collection('dates');

    const pipeline = [
      {
        $project: {
          _id: 1,
          durationDays: {
            $divide: [
              { $subtract: ["$endDate", "$startDate"] },
              1000 * 60 * 60 * 24  // Convert milliseconds to days
            ]
          }
        }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();

    console.dir(results, { depth: null });

  } finally {
    await client.close();
  }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from datetime import datetime, timedelta
from pymongo import MongoClient

def example():
  
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    try:
        db = client.test
        collection = db.dates

        pipeline = [
            {
                "$project": {
                    "_id": 1,
                    "durationDays": {
                        "$divide": [
                            { "$subtract": ["$endDate", "$startDate"] },
                            1000 * 60 * 60 * 24  # Convert milliseconds to days
                        ]
                    }
                }
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        client.close()

example()
```

------

# \$1sum
<a name="sum"></a>

The `$sum` operator in Amazon DocumentDB returns the sum of the specified expression for each document in a group. It is a group accumulator operator that is typically used in the \$1group stage of an aggregation pipeline to perform summation calculations.

**Parameters**
+ `expression`: The numeric expression to sum. This can be a field path, an expression, or a constant.

## Example (MongoDB Shell)
<a name="sum-examples"></a>

The following example demonstrates the use of the `$sum` operator to calculate the total sales for each product.

**Create sample documents**

```
db.sales.insertMany([
  { product: "abc", price: 10, quantity: 2 },
  { product: "abc", price: 10, quantity: 3 },
  { product: "xyz", price: 20, quantity: 1 },
  { product: "xyz", price: 20, quantity: 5 }
]);
```

**Query example**

```
db.sales.aggregate([
  { $group: {
      _id: "$product",
      totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } }
    }}
]);
```

**Output**

```
[
  { "_id": "abc", "totalSales": 50 },
  { "_id": "xyz", "totalSales": 120 }
]
```

## Code examples
<a name="sum-code"></a>

To view a code example for using the `$sum` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('sales');

    const result = await collection.aggregate([
      { $group: {
          _id: "$product",
          totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } }
        }}
    ]).toArray();

    console.log(result);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from pprint import pprint

def example():
    client = None
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

        db = client.test
        collection = db.sales

        result = list(collection.aggregate([
            { '$group': {
                '_id': '$product',
                'totalSales': { '$sum': { '$multiply': [ '$price', '$quantity' ] } }
            }}
        ]))

        pprint(result)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        if client:
            client.close()

example()
```

------

# \$1switch
<a name="switch"></a>

New from version 4.0.

Not supported by Elastic cluster.

The `$switch` operator is a conditional expression operator in Amazon DocumentDB that allows you to evaluate a list of case expressions and return the value of the first case that evaluates to true, or a default value if no case expression is true.

**Parameters**
+ `branches`: An array of documents, each of which has a case field that contains the boolean expression to evaluate, and a then field that contains the value to return if the case expression is true.
+ `default`: (optional) The value to return if none of the case expressions are true.

## Example (MongoDB Shell)
<a name="switch-examples"></a>

The following example demonstrates the use of the `$switch` operator to determine the shipping cost for an order based on the order total.

**Create sample documents**

```
db.orders.insertMany([
  { _id: 1, total: 50 },
  { _id: 2, total: 150 },
  { _id: 3, total: 250 }
]);
```

**Query example**

```
db.orders.aggregate([
  {
    $project: {
      _id: 1,
      total: 1,
      shippingCost: {
        $switch: {
          branches: [
            { case: { $lte: ["$total", 100] }, then: 5 },
            { case: { $lte: ["$total", 200] }, then: 10 },
            { case: { $gt: ["$total", 200] }, then: 15 }
          ],
          default: 0
        }
      }
    }
  }
])
```

**Output**

```
[
  {
    "_id": 1,
    "total": 50,
    "shippingCost": 5
  },
  {
    "_id": 2,
    "total": 150,
    "shippingCost": 10
  },
  {
    "_id": 3,
    "total": 250,
    "shippingCost": 15
  }
]
```

## Code examples
<a name="switch-code"></a>

To view a code example for using the `$switch` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        total: 1,
        shippingCost: {
          $switch: {
            branches: [
              { case: { $lte: ['$total', 100] }, then: 5 },
              { case: { $lte: ['$total', 200] }, then: 10 },
              { case: { $gt: ['$total', 200] }, then: 15 }
            ],
            default: 0
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.orders

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'total': 1,
                'shippingCost': {
                    '$switch': {
                        'branches': [
                            { 'case': { '$lte': ['$total', 100] }, 'then': 5 },
                            { 'case': { '$lte': ['$total', 200] }, 'then': 10 },
                            { 'case': { '$gt': ['$total', 200] }, 'then': 15 }
                        ],
                        'default': 0
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1toBool
<a name="toBool"></a>

The `$toBool` operator in Amazon DocumentDB converts an expression to a boolean value.

**Parameters**
+ `expression`: The expression to be converted to a boolean value.

**Note**: Any string converts to `true`.

## Example (MongoDB Shell)
<a name="toBool-examples"></a>

The following example demonstrates using the `$toBool` operator to normalize device state values from different data types.

**Create sample documents**

```
db.deviceStates.insertMany([
  { _id: 1, deviceId: "sensor-001", status: true },
  { _id: 2, deviceId: "camera-002", status: 1 },
  { _id: 3, deviceId: "thermostat-003", status: "active" },
  { _id: 4, deviceId: "doorlock-004", status: 0 }
]);
```

**Query example**

```
db.deviceStates.aggregate([
  {
    $project: {
      _id: 1,
      deviceId: 1,
      isActive: { $toBool: "$status" }
    }
  }
]);
```

**Output**

```
[
  { "_id": 1, "deviceId": "sensor-001", "isActive": true },
  { "_id": 2, "deviceId": "camera-002", "isActive": true },
  { "_id": 3, "deviceId": "thermostat-003", "isActive": true },
  { "_id": 4, "deviceId": "doorlock-004", "isActive": false }
]
```

## Code examples
<a name="toBool-code"></a>

To view a code example for using the `$toBool` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('deviceStates');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        deviceId: 1,
        isActive: { $toBool: '$status' }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['deviceStates']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'deviceId': 1,
                'isActive': { '$toBool': '$status' }
            }
        }
    ]))

    print(result)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1toDate
<a name="toDate"></a>

New from version 4.0

The `$toDate` aggregation operator in Amazon DocumentDB is used to convert a date or date and time string to a BSON Date type. This is the inverse operation of the `$dateToString` operator.

**Parameters**
+ `dateString`: A string representation of a date or date and time to be converted to a BSON Date type.
+ `format`: (optional) A string that specifies the format of the `dateString`. If not provided, the operator will attempt to parse the `dateString` in various standard date and time formats.
+ `timezone`: (optional) A string representing the time zone to use for the conversion. If not provided, the local time zone is used.

## Example (MongoDB Shell)
<a name="toDate-examples"></a>

The following example demonstrates how to use the `$toDate` operator to convert a date string to a BSON Date type.

**Create sample documents**

```
db.events.insertMany([
  { _id: 1, eventName: "Mission Start", eventTime: "2023-04-15T10:30:00Z" },
  { _id: 2, eventName: "Checkpoint Reached", eventTime: "2023-04-15T11:15:00Z" },
  { _id: 3, eventName: "Mission End", eventTime: "2023-04-15T12:00:00Z" }
]);
```

**Query example**

```
db.events.aggregate([
  {
    $project: {
      eventName: 1,
      eventTimeDate: { $toDate: "$eventTime" }
    }
  }
]);
```

**Output**

```
[
  {
    "_id": 1,
    "eventName": "Mission Start",
    "eventTimeDate": ISODate("2023-04-15T10:30:00Z")
  },
  {
    "_id": 2,
    "eventName": "Checkpoint Reached",
    "eventTimeDate": ISODate("2023-04-15T11:15:00Z")
  },
  {
    "_id": 3,
    "eventName": "Mission End",
    "eventTimeDate": ISODate("2023-04-15T12:00:00Z")
  }
]
```

## Code examples
<a name="toDate-code"></a>

To view a code example for using the `$toDate` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  const result = await collection.aggregate([
    {
      $project: {
        eventName: 1,
        eventTimeDate: { $toDate: '$eventTime' }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    result = list(collection.aggregate([
        {
            '$project': {
                'eventName': 1,
                'eventTimeDate': { '$toDate': '$eventTime' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toDecimal
<a name="toDecimal"></a>

New from version 4.0

The `$toDecimal` operator in Amazon DocumentDB is used to convert a value to the Decimal128 data type. This is useful when you need to perform precise decimal arithmetic or handle large decimal values that cannot be accurately represented using the Double data type.

**Parameters**
+ `expression`: The expression to convert to the Decimal128 data type.

## Example (MongoDB Shell)
<a name="toDecimal-examples"></a>

This example demonstrates how to use the `$toDecimal` operator to convert a string value to a Decimal128 data type.

**Create sample documents**

```
db.numbers.insertOne({ _id: 1, value: "3.14" });
db.numbers.insertOne({ _id: 2, value: "2.71" });
```

**Query example**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    decimalValue: { $toDecimal: "$value" }
  }}
])
```

**Output**

```
[
  { "_id" : 1, "decimalValue" : Decimal128("3.14") },
  { "_id" : 2, "decimalValue" : Decimal128("2.71") }
]
```

## Code examples
<a name="toDecimal-code"></a>

To view a code example for using the `$toDecimal` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      _id: 1,
      decimalValue: { $toDecimal: "$value" }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.numbers

    result = list(collection.aggregate([
        {'$project': {
            '_id': 1,
            'decimalValue': {'$toDecimal': '$value'}
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toDouble
<a name="toDouble"></a>

New from version 4.0

The `$toDouble` operator in Amazon DocumentDB is used to convert a value to a double-precision 64-bit floating-point number. This can be useful when you need to perform arithmetic operations on values that are not originally in a numeric format.

**Parameters**

`&lt;expression&gt;`: The expression to convert to a double value. This can be any valid expression that resolves to a numeric, string, or boolean value.

## Example (MongoDB Shell)
<a name="toDouble-examples"></a>

This example demonstrates how to use the `$toDouble` operator to convert a string value to a numeric value for the purpose of performing a mathematical calculation.

**Create sample documents**

```
db.numbers.insertMany([
  { _id: 1, value: "10.5" },
  { _id: 2, value: "20.25" },
  { _id: 3, value: "7" }
])
```

**Query example**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      value: 1,
      double_value: { $toDouble: "$value" },
      double_plus_five: { $add: [{ $toDouble: "$value" }, 5] }
    }
  }
])
```

**Output**

```
[
  { "_id" : 1, "value" : "10.5", "double_value" : 10.5, "double_plus_five" : 15.5 },
  { "_id" : 2, "value" : "20.25", "double_value" : 20.25, "double_plus_five" : 25.25 },
  { "_id" : 3, "value" : "7", "double_value" : 7.0, "double_plus_five" : 12.0 }
]
```

## Code examples
<a name="toDouble-code"></a>

To view a code example for using the `$toDouble` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        value: 1,
        double_value: { $toDouble: "$value" },
        double_plus_five: { $add: [{ $toDouble: "$value" }, 5] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'value': 1,
                'double_value': { '$toDouble': '$value' },
                'double_plus_five': { '$add': [{ '$toDouble': '$value' }, 5] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toInt
<a name="toInt"></a>

New from version 4.0

The `$toInt` operator in Amazon DocumentDB is used to convert an input value to an integer data type. This operator is useful when you need to ensure that a field or expression is represented as an integer, which can be important for certain operations or data processing tasks.

**Parameters**
+ `expression`: The expression to be converted to an integer.

## Example (MongoDB Shell)
<a name="toInt-examples"></a>

The following example demonstrates how to use the `$toInt` operator to convert a string value to an integer.

**Create sample documents**

```
db.numbers.insertMany([
  { "name": "one", "value": "1" },
  { "name": "hundred", "value": "100" }
]);
```

**Query example**

```
db.numbers.aggregate([
  { $project: {
    "_id": 0,
    "name": 1,
    "intValue": { $toInt: "$value" }
  }}
]);
```

**Output**

```
{ "name": "one", "intValue": 1 }
{ "name": "hundred", "intValue": 100 }
```

## Code examples
<a name="toInt-code"></a>

To view a code example for using the `$toInt` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      "_id": 0,
      "name": 1,
      "intValue": { $toInt: "$value" }
    }}
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        { "$project": {
            "_id": 0,
            "name": 1,
            "intValue": { "$toInt": "$value" }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toLong
<a name="toLong"></a>

New from version 4.0

The `$toLong` operator in Amazon DocumentDB is used to convert a value to a 64-bit integer (long) data type. This can be useful when you need to perform arithmetic operations or comparisons on numeric values that may be stored as strings or other data types.

**Parameters**
+ `expression`: The expression to convert to a 64-bit integer.

## Example (MongoDB Shell)
<a name="toLong-examples"></a>

This example demonstrates how to use the `$toLong` operator to convert a string value to a 64-bit integer.

**Create sample documents**

```
db.numbers.insertMany([
  { _id: 1, value: "42" },
  { _id: 3, value: "9223372036854775807" }
]);
```

**Query example**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      longValue: { $toLong: "$value" }
    }
  }
])
```

**Output**

```
[
  { "_id" : 1, "longValue" : 42 },
  { "_id" : 3, "longValue" : 9223372036854775807 }
]
```

## Code examples
<a name="toLong-code"></a>

To view a code example for using the `$toLong` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const numbers = db.collection('numbers');

  const result = await numbers.aggregate([
    {
      $project: {
        _id: 1,
        longValue: { $toLong: "$value" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    numbers = db.numbers

    result = list(numbers.aggregate([
        {
            '$project': {
                '_id': 1,
                'longValue': { '$toLong': '$value' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toLower
<a name="toLower"></a>

The `$toLower` operator in Amazon DocumentDB is used to convert a string to lowercase.

**Parameters**
+ `expression`: The string expression to convert to lowercase.

## Example (MongoDB Shell)
<a name="toLower-examples"></a>

The following example demonstrates how to use the `$toLower` operator to convert the `Desk` field to lowercase.

**Create sample documents**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" }
]);
```

**Query example**

```
db.locations.aggregate([
  { $project: { item: { $toLower: "$Desk" } } }
]);
```

**Output**

```
{ "_id" : 1, "item" : "düsseldorf-bvv-021" }
{ "_id" : 2, "item" : "munich-hgg-32a" }
```

## Code examples
<a name="toLower-code"></a>

To view a code example for using the `$toLower` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function main() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const collection = db.collection("locations");

  const result = await collection.aggregate([
    { $project: { item: { $toLower: "$Desk" } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    collection = db["locations"]

    result = list(collection.aggregate([
        { "$project": { "item": { "$toLower": "$Desk" } } }
    ]))

    print(result)

    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1toObjectId
<a name="toObjectId"></a>

New from version 4.0

The `$toObjectId` operator in Amazon DocumentDB is used to convert a string representation of an ObjectId to an actual ObjectId data type. This can be useful when working with data that has been stored as string representations of ObjectIds, as it allows you to perform operations that require the ObjectId data type.

**Parameters**
+ `expression`: A string expression representing a valid ObjectId.

## Example (MongoDB Shell)
<a name="toObjectId-examples"></a>

The following example demonstrates how to use the `$toObjectId` operator to convert a string representation of an ObjectId to the ObjectId data type.

**Create sample documents**

```
db.employees.insertMany([
  { _id: 1, empId:"64e5f8886218c620cf0e8f8a", name: "Carol Smith", employeeId: "c720a" },
  { _id: 2, empId:"64e5f94e6218c620cf0e8f8c", name: "Bill Taylor", employeeId: "c721a" }
]);
```

**Query example**

```
db.employees.aggregate([
  { $project: {
    "empIdAsObjectId": {$toObjectId: "$empId"}}
  }
]);
```

**Output**

```
[
  { _id: 1, empIdAsObjectId: ObjectId('64e5f8886218c620cf0e8f8a') },
  { _id: 2, empIdAsObjectId: ObjectId('64e5f94e6218c620cf0e8f8c') }
]
```

## Code examples
<a name="toObjectId-code"></a>

To view a code example for using the `$toObjectId` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('employees');

  const result = await collection.aggregate([
    { $project: {
      "empIdAsObjectId": {$toObjectId: "$empId"}}
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['employees']

    result = list(collection.aggregate([
      { "$project": {
        "empIdAsObjectId": {"$toObjectId": "$empId"}}
      }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toString
<a name="toString"></a>

New from version 4.0

The `$toString` operator in Amazon DocumentDB is used to convert a value of any type (except for null) to a string representation. This can be useful when you need to perform string operations on values that are not originally in string format.

**Parameters**
+ `expression`: The expression to convert to a string.

## Example (MongoDB Shell)
<a name="toString-examples"></a>

The following example demonstrates how to use the `$toString` operator to convert numeric values to strings.

**Create sample documents**

```
db.numbers.insertMany([
  { "_id": 1, "value": 42 },
  { "_id": 2, "value": 3.14 }
]);
```

**Query example**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    valueAsString: { $toString: "$value" }
  }}
]);
```

**Output**

```
{ "_id": 1, "valueAsString": "42" }
{ "_id": 2, "valueAsString": "3.14" }
```

## Code examples
<a name="toString-code"></a>

To view a code example for using the `$toString` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      _id: 1,
      valueAsString: { $toString: '$value' }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        { '$project': {
            '_id': 1,
            'valueAsString': { '$toString': '$value' }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toUpper
<a name="toUpper"></a>

The `$toUpper` operator in Amazon DocumentDB is used to convert a string to uppercase.

**Parameters**
+ `expression`: The string expression to convert to uppercase.

## Example (MongoDB Shell)
<a name="toUpper-examples"></a>

The following example demonstrates the usage of the `$toUpper` operator to convert the `Desk` field to uppercase.

**Create sample documents**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "düsseldorf-bvv-021" },
  { "_id": 2, "Desk": "munich-hgg-32a" }
]);
```

**Query example**

```
db.locations.aggregate([
  { $project: { item: { $toUpper: "$Desk" } } }
]);
```

**Output**

```
{ "_id" : 1, "item" : "DüSSELDORF-BVV-021" }
{ "_id" : 2, "item" : "MUNICH-HGG-32A" }
```

## Code examples
<a name="toUpper-code"></a>

To view a code example for using the `$toUpper` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('locations');

  const result = await collection.aggregate([
    { $project: { item: { $toUpper: '$Desk' } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['locations']

    result = list(collection.aggregate([
        { '$project': { 'item': { '$toUpper': '$Desk' } } }
    ]))

    print(result)

    client.close()

example()
```

------

# \$1trim
<a name="trim"></a>

New from version 4.0

The `$trim` operator in Amazon DocumentDB is used to remove leading and/or trailing whitespace characters from a string.

**Parameters**
+ `input`: The string expression to trim.
+ `chars`: (optional) Specifies the characters to trim from the beginning and end of the input, the default is whitespace.

## Example (MongoDB Shell)
<a name="trim-examples"></a>

The following example demonstrates how to use the `$trim` operator to remove leading and trailing whitespace from a string.

**Create sample documents**

```
db.people.insertMany([
  { "name": "   John Doe   " },
  { "name": "   Bob Johnson   " }
])
```

**Query example**

```
db.people.aggregate([
  { $project: {
    "name": { $trim: {input: "$name"}}
  }}
])
```

**Output**

```
[
  { "name": "John Doe" },
  { "name": "Bob Johnson" }
]
```

## Code examples
<a name="trim-code"></a>

To view a code example for using the `$trim` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    { $project: {
      "name": { $trim: {input: "$name" }}
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']

    result = list(collection.aggregate([
        {"$project": {
            "name": {"$trim": {"input": "$name"}}
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1type
<a name="type-aggregation"></a>

The `$type` aggregation operator returns the BSON data type of a specified field. This is useful for identifying the data type of field values during aggregation operations.

**Parameters**
+ `expression`: The field or expression whose type to return.

## Example (MongoDB Shell)
<a name="type-aggregation-examples"></a>

The following example demonstrates using the `$type` operator to identify the data type of the price field for each product.

**Create sample documents**

```
db.inventory.insertMany([
  { _id: 1, item: "Notebook", price: 15.99 },
  { _id: 2, item: "Pen", price: "2.50" },
  { _id: 3, item: "Eraser", price: 1 },
  { _id: 4, item: "Ruler", price: null }
]);
```

**Query example**

```
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      price: 1,
      priceType: { $type: "$price" }
    }
  }
]);
```

**Output**

```
[
  { _id: 1, item: 'Notebook', price: 15.99, priceType: 'double' },
  { _id: 2, item: 'Pen', price: '2.50', priceType: 'string' },
  { _id: 3, item: 'Eraser', price: 1, priceType: 'int' },
  { _id: 4, item: 'Ruler', price: null, priceType: 'null' }
]
```

## Code examples
<a name="type-aggregation-code"></a>

To view a code example for using the `$type` aggregation operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        price: 1,
        priceType: { $type: "$price" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'price': 1,
                'priceType': { '$type': '$price' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1unset
<a name="unset-stage"></a>

New from version 8.0

Not supported by Elastic cluster.

The `$unset` aggregation stage in Amazon DocumentDB allows you to remove fields from documents.

**Parameters**
+ `expression`: Field name or list of multiple field names.

## Example (MongoDB Shell)
<a name="unset-stage-examples"></a>

The following example demonstrates the use of the `$unset` aggregation stage to remove the `price` field.

**Create sample documents**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**Aggregation example**

```
db.inventory.aggregate([
  {
    $unset: "price"
  }
])
```

**Output**

```
[
  {
    _id: ObjectId('69248951d66dcae121d2950d'),
    item: 'pencil',
    quantity: 100
  },
  {
    _id: ObjectId('69248951d66dcae121d2950e'),
    item: 'pen',
    quantity: 204
  }
]
```

## Code examples
<a name="unset-stage-code"></a>

To view a code example for using the `$unset` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const inventory = db.collection('inventory');

  const result = await inventory.aggregate([
      {
        $unset: "price"
      }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    inventory = db['inventory']

    result = list(inventory.aggregate([
      {
        "$unset": "price"
      }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1unwind
<a name="unwind"></a>

The `$unwind` operator is used to deconstruct an array field from the input documents to output a document for each element. This can be useful when you want to perform operations on the individual elements of an array, such as filtering, sorting, or transforming the data.

**Parameters**
+ `path`: The path to the array field to be unwound.
+ `includeArrayIndex`: (optional) Specifies the name of the new field to hold the index of the array element.
+ `preserveNullAndEmptyArrays`: (optional) Determines whether the operation keeps the original document when the array field is null or an empty array.

## Example (MongoDB Shell)
<a name="unwind-examples"></a>

The following example demonstrates how to use the `$unwind` operator to deconstruct an array field and perform further operations on the individual elements.

**Create sample documents**

```
db.people.insertMany([
  { _id: 1, name: "jon", hobbies: ["painting", "dancing", "singing"] },
  { _id: 2, name: "jane", hobbies: ["reading", "swimming"] },
  { _id: 3, name: "jack", hobbies: [] }
])
```

**Query example**

```
db.people.aggregate([
  { $unwind: "$hobbies" }
])
```

**Output**

```
[
  { _id: 1, name: 'jon', hobbies: 'painting' },
  { _id: 1, name: 'jon', hobbies: 'dancing' },
  { _id: 1, name: 'jon', hobbies: 'singing' },
  { _id: 2, name: 'jane', hobbies: 'reading' },
  { _id: 2, name: 'jane', hobbies: 'swimming' }
]
```

## Code examples
<a name="unwind-code"></a>

To view a code example for using the `$unwind` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    { $unwind: '$hobbies' }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']

    result = list(collection.aggregate([
        { '$unwind': '$hobbies' }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1vectorSearch
<a name="vectorSearch"></a>

New from version 8.0

Not supported by Elastic cluster.

The `$vectorSearch` operator in Amazon DocumentDB allows you to perform vector search, a method used in machine learning to find similar data points by comparing their vector representations using distance or similarity metrics. This capability combines the flexibility and rich querying of a JSON-based document database with the power of vector search, enabling you to build machine learning and generative AI use cases such as semantic search, product recommendation, and more.

**Parameters**
+ `<exact>` (optional): Flag that specifies whether to run Exact Nearest Neighbor (ENN) or Approximate Nearest Neighbor (ANN) search. Value can be one of the following:
+ false - to run ANN search
+ true - to run ENN search

If omitted or set to false, `numCandidates` is required.

```
- `<index>` : Name of the Vector Search index to use.
- `<limit>` : Number of documents to return in the results.
- `<numCandidates>` (optional): This field is required if 'exact' is false or omitted. Number of nearest neighbors to use during the search. Value must be less than or equal to (<=) 10000. You can't specify a number less than the number of documents to return ('limit').
- `<path>` : Indexed vector type field to search.
- `<queryVector>` : Array of numbers that represent the query vector.
```

## Example (MongoDB Shell)
<a name="vectorSearch-examples"></a>

The following example demonstrates how to use the `$vectorSearch` operator to find similar product descriptions based on their vector representations.

**Create sample documents**

```
db.products.insertMany([
  {
    _id: 1,
    name: "Product A",
    description: "A high-quality, eco-friendly product for your home.",
    description_vector: [ 0.2, 0.5, 0.8 ]
  },
  {
    _id: 2,
    name: "Product B",
    description: "An innovative and modern kitchen appliance.",
    description_vector: [0.7, 0.3, 0.9]
  },
  {
    _id: 3,
    name: "Product C",
    description: "A comfortable and stylish piece of furniture.",
    description_vector: [0.1, 0.2, 0.4]
  }
]);
```

**Create vector search index**

```
db.runCommand(
    {
        createIndexes: "products",
        indexes: [{
            key: {
                "description_vector": "vector"
            },
            vectorOptions: {
                type: "hnsw",
                dimensions: 3,
                similarity: "cosine",
                m: 16,
                efConstruction: 64
            },
            name: "description_index"
        }]
    }
);
```

**Query example**

```
db.products.aggregate([
  { $vectorSearch: {
      index: "description_index",
      limit: 2,
      numCandidates: 10,
      path: "description_vector",
      queryVector: [0.1, 0.2, 0.3]
    }
  }
]);
```

**Output**

```
[
  {
    "_id": 1,
    "name": "Product A",
    "description": "A high-quality, eco-friendly product for your home.",
    "description_vector": [ 0.2, 0.5, 0.8 ]
  },
  {
    "_id": 3,
    "name": "Product C",
    "description": "A comfortable and stylish piece of furniture.",
    "description_vector": [ 0.1, 0.2, 0.4 ]
  }
]
```

## Code examples
<a name="vectorSearch-code"></a>

To view a code example for using the `$vectorSearch` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findSimilarProducts(queryVector) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.aggregate([
    { $vectorSearch: {
        index: "description_index",
        limit: 2,
        numCandidates: 10,
        path: "description_vector",
        queryVector: queryVector
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

findSimilarProducts([0.1, 0.2, 0.3]);
```

------
#### [ Python ]

```
from pymongo import MongoClient


def find_similar_products(query_vector):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    result = list(collection.aggregate([
        {
            '$vectorSearch': {
                'index': "description_index",
                'limit': 2,
                'numCandidates': 10,
                'path': "description_vector",
                'queryVector': query_vector
            }
        }
    ]))

    print(result)
    client.close()

find_similar_products([0.1, 0.2, 0.3])
```

------

# \$1week
<a name="week"></a>

The `$week` operator in Amazon DocumentDB returns the week number of a date (0-53) based on the ISO 8601 standard. The week number is calculated based on the year and the day of the week, with Monday as the first day of the week.

**Parameters**

None

## Example (MongoDB Shell)
<a name="week-examples"></a>

The following example demonstrates how to use the `$week` operator to retrieve the week number of a given date.

**Create sample documents**

```
db.events.insertMany([
  { _id: 1, date: new Date("2023-01-01") },
  { _id: 2, date: new Date("2023-01-08") },
  { _id: 3, date: new Date("2023-12-31") }
]);
```

**Query example**

```
db.events.aggregate([
  { $project: {
    _id: 1,
    week: { $week: "$date" }
  }}
]);
```

**Output**

```
[
  { "_id": 1, "week": 1 },
  { "_id": 2, "week": 2 },
  { "_id": 3, "week": 53 }
]
```

## Code examples
<a name="week-code"></a>

To view a code example for using the `$week` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('events');

  const result = await events.aggregate([
    { $project: {
      _id: 1,
      week: { $week: "$date" }
    }}
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
  db = client['test']
  events = db['events']

  result = list(events.aggregate([
      {'$project': {
          '_id': 1,
          'week': {'$week': '$date'}
      }}
  ]))

  print(result)

  client.close()

example()
```

------

# \$1year
<a name="year"></a>

The `$year` operator in Amazon DocumentDB extracts the year component from a date or timestamp.

**Parameters**
+ `expression`: The date or timestamp expression from which to extract the year component.

## Example (MongoDB Shell)
<a name="year-examples"></a>

The following example demonstrates how to use the `$year` operator to extract the year component from a date field.

**Create sample documents**

```
db.events.insertMany([
  { "_id": 1, "date": ISODate("2023-04-15T00:00:00Z") },
  { "_id": 3, "date": ISODate("2021-12-31T00:00:00Z") }
]);
```

**Query example**

```
db.events.aggregate([
  { $project: { year: { $year: "$date" } } }
]);
```

**Output**

```
[
  { "_id": 1, "year": 2023 },
  { "_id": 3, "year": 2021 }
]
```

## Code examples
<a name="year-code"></a>

To view a code example for using the `$year` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  const result = await collection.aggregate([
    { $project: { year: { $year: "$date" } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    result = list(collection.aggregate([
        {'$project': {'year': {'$year': '$date'}}}
    ]))

    print(result)

    client.close()

example()
```

------

# \$1zip
<a name="zip"></a>

The `$zip` operator in Amazon DocumentDB allows you to combine multiple arrays into a single array of tuples (key-value pairs). This is useful when you need to create new documents or objects by combining data from different sources or arrays within a document.

**Parameters**
+ `inputs`: An array of expressions that resolve to arrays. These arrays will be combined into a single array of tuples.
+ `useLongestLength`: (optional) If `true`, the output array will have the length of the longest input array, padding shorter arrays with `null` values. If `false`, the output array will have the length of the shortest input array.
+ `defaults`: (optional) An array of default values to use for the tuples if the corresponding input array is shorter than the longest input array and `useLongestLength` is `true`.

## Example (MongoDB Shell)
<a name="zip-examples"></a>

The following example demonstrates how to use the `$zip` operator to combine two arrays into a single array of tuples.

**Create sample documents**

```
db.grades.insert([
  {
    "_id": 1,
    "name": "John",
    "scores": [90, 85, 92],
    "classes": ["Math", "English", "Science"]
  },
  {
    "_id": 2,
    "name": "Jane",
    "scores": [88, 91, 90, 85],
    "classes": ["Math", "English", "Science", "History"]
  }
])
```

**Query example**

```
db.grades.aggregate([
  {
    $project: {
      "name": 1,
      "scoredClasses": {
        $zip: {
          inputs: ["$scores", "$classes"],
          useLongestLength: true,
          defaults: [null, null]
        }
      }
    }
  }
])
```

**Output**

```
[
  {
    "_id": 1,
    "name": "John",
    "scoredClasses": [
      [90, "Math"],
      [85, "English"],
      [92, "Science"],
      [null, null]
    ]
  },
  {
    "_id": 2,
    "name": "Jane",
    "scoredClasses": [
      [88, "Math"],
      [91, "English"],
      [90, "Science"],
      [85, "History"]
    ]
  }
]
```

## Code examples
<a name="zip-code"></a>

To view a code example for using the `$zip` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('grades');

  const result = await collection.aggregate([
    {
      $project: {
        "name": 1,
        "scoredClasses": {
          $zip: {
            inputs: ["$scores", "$classes"],
            useLongestLength: true,
            defaults: [null, null]
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['grades']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'scoredClasses': {
                    '$zip': {
                        'inputs': ['$scores', '$classes'],
                        'useLongestLength': True,
                        'defaults': [None, None]
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# Geospatial
<a name="mongo-apis-geospatial-operators"></a>

This section provides detailed information about geospatial operators supported by Amazon DocumentDB.

**Topics**
+ [\$1geometry](geometry.md)
+ [\$1geoIntersects](geoIntersects.md)
+ [\$1geoWithin](geoWithin.md)
+ [\$1maxDistance](maxDistance.md)
+ [\$1minDistance](minDistance.md)
+ [\$1near](near.md)
+ [\$1nearSphere](nearSphere.md)

# \$1geometry
<a name="geometry"></a>

The `$geometry` operator in Amazon DocumentDB is used to specify a GeoJSON geometry object as part of a geospatial query. This operator is used in conjunction with other geospatial query operators like `$geoWithin` and `$geoIntersects` to perform spatial queries on your data.

In Amazon DocumentDB, the `$geometry` operator supports the following GeoJSON geometry types:
+ Point
+ LineString
+ Polygon
+ MultiPoint
+ MultiLineString
+ MultiPolygon
+ GeometryCollection

**Parameters**
+ `type`: The type of the GeoJSON geometry object, e.g., `Point`, `Polygon`, etc.
+ `coordinates`: An array of coordinates representing the geometry. The structure of the coordinates array depends on the geometry type.

## Example (MongoDB Shell)
<a name="geometry-examples"></a>

The following example demonstrates how to use the `$geometry` operator to perform a `$geoIntersects` query in Amazon DocumentDB.

**Create sample documents**

```
db.locations.insertMany([
  { 
    "_id": 1,
    "name": "Location 1",
    "location": { 
      "type": "Point",
      "coordinates": [-73.983253, 40.753941]
    }
  },
  { 
    "_id": 2,
    "name": "Location 2", 
    "location": {
      "type": "Polygon",
      "coordinates": [[
        [-73.998427, 40.730309],
        [-73.954348, 40.730309],
        [-73.954348, 40.780816],
        [-73.998427, 40.780816],
        [-73.998427, 40.730309]
      ]]
    }
  }
]);
```

**Query example**

```
db.locations.find({
  "location": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Polygon",
        "coordinates": [[
          [-73.998, 40.730],
          [-73.954, 40.730],
          [-73.954, 40.781],
          [-73.998, 40.781],
          [-73.998, 40.730]
        ]]
      }
    }
  }
})
```

**Output**

```
[
  {
    "_id": 2,
    "name": "Location 2",
    "location": {
      "type": "Polygon",
      "coordinates": [
        [
          [-73.998427, 40.730309],
          [-73.954348, 40.730309],
          [-73.954348, 40.780816],
          [-73.998427, 40.780816],
          [-73.998427, 40.730309]
        ]
      ]
    }
  }
]
```

## Code examples
<a name="geometry-code"></a>

To view a code example for using the `$geometry` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('locations');

  const query = {
    "location": {
      "$geoIntersects": {
        "$geometry": {
          "type": "Polygon",
          "coordinates": [[
            [-73.998, 40.730],
            [-73.954, 40.730],
            [-73.954, 40.781],
            [-73.998, 40.781],
            [-73.998, 40.730]
          ]]
        }
      }
    }
  };

  const result = await collection.find(query).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['locations']

    query = {
        "location": {
            "$geoIntersects": {
                "$geometry": {
                    "type": "Polygon",
                    "coordinates": [[
                        [-73.998, 40.730],
                        [-73.954, 40.730],
                        [-73.954, 40.781],
                        [-73.998, 40.781],
                        [-73.998, 40.730]
                    ]]
                }
            }
        }
    }

    result = list(collection.find(query))
    print(result)

    client.close()

example()
```

------

# \$1geoIntersects
<a name="geoIntersects"></a>

The `$geoIntersects` operator in Amazon DocumentDB is used to find documents whose geospatial data intersects with a specified GeoJSON object. This operator is useful for applications that require identifying documents based on their spatial relationship with a given geographic shape, such as a polygon or multipolygon.

**Parameters**
+ `$geometry`: A GeoJSON object that represents the shape to check for intersection. The supported GeoJSON object types are `Point`, `LineString`, `Polygon`, and `MultiPolygon`.

## Example (MongoDB Shell)
<a name="geoIntersects-examples"></a>

The following example demonstrates how to use the `$geoIntersects` operator to find the state name for a given set of coordinates in Amazon DocumentDB.

**Create sample documents**

```
db.states.insertMany([
  {
    "name": "New York",
    "loc": {
      "type": "Polygon",
      "coordinates": [[
        [-74.25909423828125, 40.47556838210948],
        [-73.70819091796875, 40.47556838210948],
        [-73.70819091796875, 41.31342607582222],
        [-74.25909423828125, 41.31342607582222],
        [-74.25909423828125, 40.47556838210948]
      ]]
    }
  },
  {
    "name": "California",
    "loc": {
      "type": "Polygon",
      "coordinates": [[
        [-124.4091796875, 32.56456771381587],
        [-114.5458984375, 32.56456771381587],
        [-114.5458984375, 42.00964153424558],
        [-124.4091796875, 42.00964153424558],
        [-124.4091796875, 32.56456771381587]
      ]]
    }
  }
]);
```

**Query example**

```
var location = [-73.965355, 40.782865];

db.states.find({
  "loc": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Point",
        "coordinates": location
      }
    }
  }
}, {
  "name": 1
});
```

**Output**

```
{ "_id" : ObjectId("536b0a143004b15885c91a2c"), "name" : "New York" }
```

## Code examples
<a name="geoIntersects-code"></a>

To view a code example for using the `$geoIntersects` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findStateByGeoIntersects(longitude, latitude) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('states');

  const query = {
    loc: {
      $geoIntersects: {
        $geometry: {
          type: 'Point',
          coordinates: [longitude, latitude]
        }
      }
    }
  };

  const projection = {
    _id: 0,
    name: 1
  };

  const document = await collection.findOne(query, { projection });

  await client.close();
  
  if (document) {
    return document.name;
  } else {
    throw new Error('The geo location you entered was not found in the United States!');
  }
}
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_state_by_geointersects(longitude, latitude):
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        db = client.test
        collection_states = db.states

        query_geointersects = {
            "loc": {
                "$geoIntersects": {
                    "$geometry": {
                        "type": "Point",
                        "coordinates": [longitude, latitude]
                    }
                }
            }
        }

        document = collection_states.find_one(query_geointersects,
                                              projection={
                                                  "_id": 0,
                                                  "name": 1
                                              })
        if document is not None:
            state_name = document['name']
            return state_name
        else:
            raise Exception("The geo location you entered was not found in the United States!")
    except Exception as e:
        print('Exception in geoIntersects: {}'.format(e))
        raise
    finally:
        if client is not None:
            client.close()
```

------

# \$1geoWithin
<a name="geoWithin"></a>

The `$geoWithin` operator in Amazon DocumentDB is used to find documents whose location data (represented as GeoJSON objects) are completely contained within a specified shape, such as a polygon or multipolygon. This is useful for querying for objects that are located within a specific geographic region.

**Parameters**
+ `$geometry`: A GeoJSON object that represents the shape to query against.

## Example (MongoDB Shell)
<a name="geoWithin-examples"></a>

The following example demonstrates how to use the `$geoWithin` operator to find all airports located within the state of New York.

**Create sample documents**

```
// Insert state document
db.states.insert({
    "name": "New York",
    "loc": {
        "type": "Polygon",
        "coordinates": [[
            [-79.76278, 45.0],
            [-73.94, 45.0],
            [-73.94, 40.5],
            [-79.76278, 40.5],
            [-79.76278, 45.0]
        ]]
    }
});

// Insert airport documents
db.airports.insert([
    {
        "name": "John F. Kennedy International Airport",
        "type": "airport",
        "code": "JFK",
        "loc": {
            "type": "Point",
            "coordinates": [-73.7781, 40.6413]
        }
    },
    {
        "name": "LaGuardia Airport",
        "type": "airport",
        "code": "LGA",
        "loc": {
            "type": "Point",
            "coordinates": [-73.8772, 40.7769]
        }
    },
    {
        "name": "Buffalo Niagara International Airport",
        "type": "airport",
        "code": "BUF",
        "loc": {
            "type": "Point",
            "coordinates": [-78.7322, 42.9403]
        }
    }
]);
```

**Query example**

```
var state = db.states.findOne({"name": "New York"});

db.airports.find({
    "loc": {
        "$geoWithin": {
            "$geometry": state.loc
        }
    }
}, {
    "name": 1,
    "type": 1,
    "code": 1,
    "_id": 0
});
```

**Output**

```
[
  {
    "name": "John F. Kennedy International Airport",
    "type": "airport",
    "code": "JFK"
  },
  {
    "name": "LaGuardia Airport",
    "type": "airport",
    "code": "LGA"
  }
]
```

## Code examples
<a name="geoWithin-code"></a>

To view a code example for using the `$geoWithin` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findAirportsWithinState(stateName) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');

  const stateDoc = await db.collection('states').findOne({ name: stateName }, { projection: { _id: 0, loc: 1 } });
  const airportDocs = await db.collection('airports').find({
    loc: {
      $geoWithin: {
        $geometry: stateDoc.loc
      }
    }
  }, { projection: { name: 1, type: 1, code: 1, _id: 0 } }).toArray();

  console.log(airportDocs);

  await client.close();
}

findAirportsWithinState('New York');
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_airports_within_state(state_name):
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        db = client['test']
        state_doc = db.states.find_one({'name': state_name}, {'_id': 0, 'loc': 1})
        airport_docs = db.airports.find({
            'loc': {
                '$geoWithin': {
                    '$geometry': state_doc['loc']
                }
            }
        }, {'name': 1, 'type': 1, 'code': 1, '_id': 0})
        
        return list(airport_docs)
    except Exception as e:
        print(f'Error: {e}')
    finally:
        client.close()

airports = find_airports_within_state('New York')
print(airports)
```

------

# \$1maxDistance
<a name="maxDistance"></a>

The `$maxDistance` operator in Amazon DocumentDB is used to specify the maximum distance (in meters) from a GeoJSON point that documents must be within to be included in the query results. This operator is used in conjunction with the `$nearSphere` operator to perform geospatial queries.

**Parameters**
+ `$maxDistance`: The maximum distance (in meters) from the reference point that documents must be within to be included in the query results.

## Example (MongoDB Shell)
<a name="maxDistance-examples"></a>

The following example demonstrates how to use the `$maxDistance` operator in Amazon DocumentDB to find all state capitals within 100 kilometers of Boston.

**Create sample documents**

```
db.capitals.insert([
  { state: "Massachusetts", city: "Boston", location: { type: "Point", coordinates: [-71.0589, 42.3601] } },
  { state: "Rhode Island", city: "Providence", location: { type: "Point", coordinates: [-71.4128, 41.8239] } },
  { state: "New Hampshire", city: "Concord", location: { type: "Point", coordinates: [-71.5383, 43.2067] } },
  { state: "Vermont", city: "Montpelier", location: { type: "Point", coordinates: [-72.5751, 44.2604] } }
]);
```

**Query example**

```
db.capitals.find(
  {
    location: {
      $nearSphere: {
        $geometry: { type: "Point", coordinates: [-71.0589, 42.3601] },
        $maxDistance: 100000
      }
    }
  },
  { state: 1, city: 1, _id: 0 }
);
```

**Output**

```
[
  { "state": "Rhode Island", "city": "Providence" },
  { "state": "New Hampshire", "city": "Concord" }
]
```

## Code examples
<a name="maxDistance-code"></a>

To view a code example for using the `$maxDistance` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findCapitalsNearBoston() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const capitals = db.collection('capitals');

  const result = await capitals.find({
    location: {
      $nearSphere: {
        $geometry: { type: "Point", coordinates: [-71.0589, 42.3601] },
        $maxDistance: 100000
      }
    }
  }, {
    projection: { state: 1, city: 1, _id: 0 }
  }).toArray();

  console.log(result);
  await client.close();
}

findCapitalsNearBoston();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_capitals_near_boston():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    capitals = db.capitals

    result = list(capitals.find(
        {
            "location": {
                "$nearSphere": {
                    "$geometry": { "type": "Point", "coordinates": [-71.0589, 42.3601] },
                    "$maxDistance": 100000
                }
            }
        },
        {"state": 1, "city": 1, "_id": 0}
    ))

    print(result)
    client.close()

find_capitals_near_boston()
```

------

# \$1minDistance
<a name="minDistance"></a>

`$minDistance` is a find operator used in conjunction with `$nearSphere` or `$geoNear` to filter documents that are at least at the specified minimum distance from the center point. This operator is supported in Amazon DocumentDB and functions similarly to its counterpart in MongoDB.

**Parameters**
+ `$minDistance`: The minimum distance (in meters) from the center point to include documents in the results.

## Example (MongoDB Shell)
<a name="minDistance-examples"></a>

In this example, we'll find all restaurants within a 2-kilometer radius of a specific location in Seattle, Washington.

**Create sample documents**

```
db.usarestaurants.insertMany([
  {
    "state": "Washington",
    "city": "Seattle",
    "name": "Noodle House",
    "rating": 4.8,
    "location": {
      "type": "Point",
      "coordinates": [-122.3517, 47.6159]
    }
  },
  {
    "state": "Washington",
    "city": "Seattle",
    "name": "Pike Place Grill",
    "rating": 4.5,
    "location": {
      "type": "Point",
      "coordinates": [-122.3412, 47.6102]
    }
  },
  {
    "state": "Washington",
    "city": "Bellevue",
    "name": "The Burger Joint",
    "rating": 4.2,
    "location": {
      "type": "Point",
      "coordinates": [-122.2007, 47.6105]
    }
  }
]);
```

**Query example**

```
db.usarestaurants.find({
  "location": {
    "$nearSphere": {
      "$geometry": {
        "type": "Point",
        "coordinates": [-122.3516, 47.6156]
      },
      "$minDistance": 1,
      "$maxDistance": 2000
    }
  }
}, {
  "name": 1
});
```

**Output**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## Code examples
<a name="minDistance-code"></a>

To view a code example for using the `$minDistance` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findRestaurantsNearby() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('usarestaurants');

  const result = await collection.find({
    "location": {
      "$nearSphere": {
        "$geometry": {
          "type": "Point",
          "coordinates": [-122.3516, 47.6156]
        },
        "$minDistance": 1,
        "$maxDistance": 2000
      }
    }
  }, {
    "projection": { "name": 1 }
  }).toArray();

  console.log(result);
  client.close();
}

findRestaurantsNearby();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_restaurants_nearby():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.usarestaurants

    result = list(collection.find({
        "location": {
            "$nearSphere": {
                "$geometry": {
                    "type": "Point",
                    "coordinates": [-122.3516, 47.6156]
                },
                "$minDistance": 1,
                "$maxDistance": 2000
            }
        }
    }, {
        "projection": {"name": 1}
    }))

    print(result)
    client.close()

find_restaurants_nearby()
```

------

# \$1near
<a name="near"></a>

The `$near` operator in Amazon DocumentDB is used to find documents that are geographically near a specified point. It returns documents ordered by distance, with the closest documents first. This operator requires a 2dsphere geospatial index and is useful for proximity queries on location data.

**Parameters**
+ `$geometry`: A GeoJSON Point object that defines the center point for the near query.
+ `$maxDistance`: (optional) The maximum distance in meters from the specified point that a document can be to match the query.
+ `$minDistance`: (optional) The minimum distance in meters from the specified point that a document can be to match the query.

**Index Requirements**
+ `2dsphere index`: Required for geospatial queries on GeoJSON Point data.

## Example (MongoDB Shell)
<a name="near-examples"></a>

The following example demonstrates how to use the `$near` operator to find the nearest restaurants to a specific location in Seattle, Washington.

**Create sample documents**

```
db.usarestaurants.insert([
  {
    "name": "Noodle House",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.8,
    "location": { "type": "Point", "coordinates": [-122.3517, 47.6159] }
  },
  {
    "name": "Pike Place Grill",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.2,
    "location": { "type": "Point", "coordinates": [-122.3403, 47.6062] }
  },
  {
    "name": "Lola",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.5,
    "location": { "type": "Point", "coordinates": [-122.3407, 47.6107] }
  }
]);
```

**Create 2dsphere index**

```
db.usarestaurants.createIndex({ "location": "2dsphere" });
```

**Query example with GeoJSON Point**

```
db.usarestaurants.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $maxDistance: 100,
      $minDistance: 10
    }
  }
});
```

**Output**

```
{
  "_id" : ObjectId("69031ec9ea1c2922a1ce5f4a"),
  "name" : "Noodle House",
  "city" : "Seattle",
  "state" : "Washington",
  "rating" : 4.8,
  "location" : {
    "type" : "Point",
    "coordinates" : [ -122.3517, 47.6159 ]
  }
}
```

## Code examples
<a name="near-code"></a>

To view a code example for using the `$near` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findNearbyRestaurants() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const restaurants = db.collection('usarestaurants');

  // Create 2dsphere index
  await restaurants.createIndex({ "location": "2dsphere" });

  const result = await restaurants.find({
    location: {
      $near: {
        $geometry: {
          type: "Point",
          coordinates: [-122.3516, 47.6156]
        },
        $maxDistance: 100,
        $minDistance: 10
      }
    }
  }).toArray();

  console.log(result);

  client.close();
}

findNearbyRestaurants();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_nearby_restaurants():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    restaurants = db['usarestaurants']

    # Create 2dsphere index
    restaurants.create_index([("location", "2dsphere")])

    result = list(restaurants.find({
        'location': {
            '$near': {
                '$geometry': {
                    'type': 'Point',
                    'coordinates': [-122.3516, 47.6156]
                },
                '$maxDistance': 100,
                '$minDistance': 10
            }
        }
    }))

    print(result)

    client.close()

find_nearby_restaurants()
```

------

# \$1nearSphere
<a name="nearSphere"></a>

The `$nearSphere` operator in Amazon DocumentDB is used to find documents that are within a specified distance of a geospatial point. This operator is particularly useful for geo-spatial queries, such as finding all restaurants within a certain radius of a given location.

**Parameters**
+ `$geometry`: A GeoJSON object that represents the reference point. Must be a `Point` object with `type` and `coordinates` fields.
+ `$minDistance`: (optional) The minimum distance (in meters) from the reference point that documents must be.
+ `$maxDistance`: (optional) The maximum distance (in meters) from the reference point that documents must be.

## Example (MongoDB Shell)
<a name="nearSphere-examples"></a>

In this example, we will find all restaurants within 2 kilometers (2000 meters) of a specific location in Seattle, WA.

**Create sample documents**

```
db.usarestaurants.insert([
  {
    name: "Noodle House",
    location: { type: "Point", coordinates: [-122.3516, 47.6156] }
  },
  {
    name: "Pike Place Grill",
    location: { type: "Point", coordinates: [-122.3403, 47.6101] }
  },
  {
    name: "Seattle Coffee Co.",
    location: { type: "Point", coordinates: [-122.3339, 47.6062] }
  }
]);
```

**Query example**

```
db.usarestaurants.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $minDistance: 1,
      $maxDistance: 2000
    }
  }
}, {
  name: 1
});
```

**Output**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## Code examples
<a name="nearSphere-code"></a>

To view a code example for using the `$nearSphere` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findNearbyRestaurants() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const restaurants = db.collection('usarestaurants');

  const result = await restaurants.find({
    location: {
      $nearSphere: {
        $geometry: {
          type: "Point",
          coordinates: [-122.3516, 47.6156]
        },
        $minDistance: 1,
        $maxDistance: 2000
      }
    }
  }, {
    projection: { name: 1 }
  }).toArray();

  console.log(result);
  client.close();
}

findNearbyRestaurants();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_nearby_restaurants():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    restaurants = db.usarestaurants

    result = list(restaurants.find({
        'location': {
            '$nearSphere': {
                '$geometry': {
                    'type': 'Point',
                    'coordinates': [-122.3516, 47.6156]
                },
                '$minDistance': 1,
                '$maxDistance': 2000
            }
        }
    }, {
        'name': 1
    }))

    print(result)
    client.close()

find_nearby_restaurants()
```

------

# Query and projection operators
<a name="mongo-apis-query-projection-operators"></a>

This section provides detailed information about query and projection operators supported by Amazon DocumentDB.

**Topics**
+ [\$1](dollar-projection.md)
+ [\$1all](all.md)
+ [\$1and](and.md)
+ [\$1bitsAllClear](bitsAllClear.md)
+ [\$1bitsAllSet](bitsAllSet.md)
+ [\$1bitsAnyClear](bitsAnyClear.md)
+ [\$1bitsAnySet](bitsAnySet.md)
+ [\$1comment](comment.md)
+ [\$1elemMatch](elemMatch.md)
+ [\$1eq](eq.md)
+ [\$1exists](exists.md)
+ [\$1expr](expr.md)
+ [\$1gt](gt.md)
+ [\$1gte](gte.md)
+ [\$1in](in.md)
+ [\$1jsonSchema](jsonSchema.md)
+ [\$1lt](lt.md)
+ [\$1mod](mod-query.md)
+ [\$1lte](lte.md)
+ [\$1meta](meta.md)
+ [\$1ne](ne.md)
+ [\$1nin](nin.md)
+ [\$1nor](nor.md)
+ [\$1not](not.md)
+ [\$1or](or.md)
+ [\$1regex](regex.md)
+ [\$1slice](slice-projection.md)
+ [\$1size](size-query.md)
+ [\$1text](text.md)
+ [\$1type](type.md)

# \$1
<a name="dollar-projection"></a>

The `$` projection operator limits the contents of an array field to return only the first element that matches the query condition. It is used to project a single matching array element.

**Parameters**
+ `field.$`: The array field with the positional operator to project the first matching element.

## Example (MongoDB Shell)
<a name="dollar-projection-examples"></a>

The following example demonstrates using the `$` projection operator to return only the matching array element.

**Create sample documents**

```
db.students.insertMany([
  { _id: 1, name: "Alice", grades: [85, 92, 78, 95] },
  { _id: 2, name: "Bob", grades: [70, 88, 92, 65] },
  { _id: 3, name: "Charlie", grades: [95, 89, 91, 88] }
]);
```

**Query example**

```
db.students.find(
  { grades: { $gte: 90 } },
  { name: 1, "grades.$": 1 }
);
```

**Output**

```
{ "_id" : 1, "name" : "Alice", "grades" : [ 92 ] }
{ "_id" : 2, "name" : "Bob", "grades" : [ 92 ] }
{ "_id" : 3, "name" : "Charlie", "grades" : [ 95 ] }
```

In this example, only the first grade that is greater than or equal to 90 is returned for each student.

## Code examples
<a name="dollar-projection-code"></a>

To view a code example for using the `$` projection operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  const result = await collection.find(
    { grades: { $gte: 90 } },
    { projection: { name: 1, "grades.$": 1 } }
  ).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['students']

    result = list(collection.find(
        {'grades': {'$gte': 90}},
        {'name': 1, 'grades.$': 1}
    ))

    print(result)
    client.close()

example()
```

------

# \$1all
<a name="all"></a>

The `$all` operator in Amazon DocumentDB is used to match documents where the value of a field is an array and contains all the specified elements, regardless of the order of the elements in the array.

**Parameters**
+ `field`: The name of the field to check.
+ `[value1, value2, ...]`: The list of values to match in the array.

 

**Using `$elemMatch` within an `$all` expression**

See [Using `$elemMatch` within an `$all` expression](functional-differences.md#functional-differences.elemMatch) for limitations regarding the use of the `$elemMatch` operator within an `$all` expression.

 

**Dollar (\$1) in field names**

See [Dollar(\$1) and dot(.) in field names](functional-differences.md#functional-differences-dollardot) for limitations regarding querying `$` prefixed fields in `$all` in nested objects.

## Example (MongoDB Shell)
<a name="all-examples"></a>

The following example demonstrates the usage of the `$all` operator to retrieve documents where the "Colors" field is an array that contains both "Red" and "Blue".

**Create sample documents**

```
db.example.insertMany([
  { "Item": "Pen", "Colors": ["Red", "Blue", "Green"] },
  { "Item": "Notebook", "Colors": ["Blue", "White"] },
  { "Item": "Poster Paint", "Colors": ["Red", "Yellow", "White"] }
])
```

**Query example**

```
db.example.find({ "Colors": { $all: ["Red", "Blue"] } }).pretty()
```

**Output**

```
{
  "_id" : ObjectId("6137d6c5b3a1d35e0b6ee6ad"),
  "Item" : "Pen",
  "Colors" : [ 
          "Red", 
          "Blue", 
          "Green" 
  ]
}
```

## Code examples
<a name="all-code"></a>

To view a code example for using the `$all` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  const result = await collection.find({ "Colors": { $all: ["Red", "Blue"] } }).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    result = list(collection.find({ "Colors": { "$all": ["Red", "Blue"] } }))
    print(result)

    client.close()

example()
```

------

# \$1and
<a name="and"></a>

The `$and` operator in Amazon DocumentDB is used to combine multiple expressions and evaluate them as a single condition. It returns `true` if all the provided expressions evaluate to `true`, and `false` otherwise. This operator is useful for applying multiple criteria to a query.

**Parameters**
+ `expression1`: A required expression that evaluates to a boolean value.
+ `expression2`: A required expression that evaluates to a boolean value.
+ `...`: Additional required expressions that evaluate to boolean values.

## Example (MongoDB Shell)
<a name="and-examples"></a>

The following example demonstrates the use of the `$and` operator to find all documents in the "users" collection where the "age" field is greater than 18 and the "status" field is "active".

**Create sample documents**

```
db.users.insertMany([
  { name: "John", age: 25, status: "active" },
  { name: "Jane", age: 17, status: "active" },
  { name: "Bob", age: 30, status: "inactive" },
  { name: "Alice", age: 22, status: "active" }
]);
```

**Query example**

```
db.users.find({
  $and: [
    { age: { $gt: 18 } },
    { status: "active" }
  ]
});
```

**Output**

```
[
  { "_id" : ObjectId("614e3c4b63f5892e7c4e2345"), "name" : "John", "age" : 25, "status" : "active" },
  { "_id" : ObjectId("614e3c4b63f5892e7c4e2347"), "name" : "Alice", "age" : 22, "status" : "active" }
]
```

## Code examples
<a name="and-code"></a>

To view a code example for using the `$and` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findActiveUsersOlderThan18() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const activeUsersOlderThan18 = await users.find({
    $and: [
      { age: { $gt: 18 } },
      { status: 'active' }
    ]
  }).toArray();

  console.log(activeUsersOlderThan18);
  await client.close();
}

findActiveUsersOlderThan18();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_active_users_older_than_18():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    active_users_older_than_18 = list(users.find({
        '$and': [
            {'age': {'$gt': 18}},
            {'status': 'active'}
        ]
    }))

    print(active_users_older_than_18)
    client.close()

find_active_users_older_than_18()
```

------

# \$1bitsAllClear
<a name="bitsAllClear"></a>

The `$bitsAllClear` operator in Amazon DocumentDB is used to match the documents where all the specified bits in a field are cleared (set to 0). This operator can be useful for performing bitwise operations on stored data.

**Parameters**
+ `field`: The field to check for the specified bits being cleared.
+ `value`: The numeric bitmask that specifies which bits should be checked, or a list of bits positions to be checked. A numeric bitmask can be a binary (0b...), decimal, hexadecimal (0x...), octal (0o...), or binary (BinData) form. In a list of bits positions, the position of the least significant bit is 0.

## Example (MongoDB Shell)
<a name="bitsAllClear-examples"></a>

The following example demonstrates the usage of the `$bitsAllClear` operator in Amazon DocumentDB.

**Create sample documents**

```
db.collection.insertMany([
  { _id: 1, bits: 0b1010 },
  { _id: 2, bits: 0b1100 },
  { _id: 3, bits: 0b0101 }
]);
```

**Query example**

```
db.collection.find({
  bits: { $bitsAllClear: 0b0011 }
})
```

**Output**

```
{ "_id" : 2, "bits" : 12 }
```

The query checks if all the bits specified by the bitmask `0b0011` (the two least significant bits) are cleared in the `bits` field. The document with `_id` 2 satisfies this condition, as its `bits` field has those bits cleared.

## Code examples
<a name="bitsAllClear-code"></a>

To view a code example for using the `$bitsAllClear` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.find({
    bits: { $bitsAllClear: 0b0011 }
  }).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['collection']

    result = list(collection.find({
        'bits': { '$bitsAllClear': 0b0011 }
    }))

    print(result)

    client.close()

example()
```

------

# \$1bitsAllSet
<a name="bitsAllSet"></a>

The `$bitsAllSet` operator in Amazon DocumentDB is used to query for documents where a specific set of bits are all set to 1 in a field. This operator allows you to perform bitwise operations on field values and can be useful when you need to check the state of individual bits within a numeric value.

**Parameters**
+ `field`: The name of the numeric field to perform the bitwise operation on.
+ `value`: The numeric bitmask that specifies which bits should be checked, or a list of bits positions to be checked. A numeric bitmask can be a binary (0b...), decimal, hexadecimal (0x...), octal (0o...), or binary (BinData) form. In a list of bits positions, the position of the least significant bit is 0.

## Example (MongoDB Shell)
<a name="bitsAllSet-examples"></a>

The following example demonstrates how to use the `$bitsAllSet` operator to find documents where the `flags` field has all the bits set that are specified by the bitmask.

**Create sample documents**

```
db.collection.insert([
  { _id: 1, flags: 0b1010 },
  { _id: 2, flags: 0b1100 },
  { _id: 3, flags: 0b1110 }
])
```

**Query example**

```
db.collection.find({ flags: { $bitsAllSet: 0b1100 } })
```

**Output**

```
{ "_id": 2, "flags": 12 },
{ "_id": 3, "flags": 14 }
```

In this example, the query checks for documents where the `flags` field has all the bits set that are specified by the bitmask `0b1100` (which represents the decimal value 12). The documents with `_id` 2 and 3 match this criteria, as their `flags` field values have all the required bits set (the 3rd and 4th least significant bits).

## Code examples
<a name="bitsAllSet-code"></a>

To view a code example for using the `$bitsAllSet` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findWithBitsAllSet() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.find({ flags: { $bitsAllSet: 0b1100 } }).toArray();
  console.log(result);

  await client.close();
}

findWithBitsAllSet();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_with_bits_all_set():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.collection

    result = list(collection.find({ 'flags': { '$bitsAllSet': 0b1100 } }))
    print(result)

    client.close()

find_with_bits_all_set()
```

------

# \$1bitsAnyClear
<a name="bitsAnyClear"></a>

The `$bitsAnyClear` operator in Amazon DocumentDB is used to match the documents where any of the specified bit in a field are cleared (set to 0). This can be useful for performing bitwise operations on field values stored in documents.

**Parameters**
+ `field`: The field to check.
+ `value`: The numeric bitmask that specifies which bits should be checked, or a list of bits positions to be checked. A numeric bitmask can be a binary (0b...), decimal, hexadecimal (0x...), octal (0o...), or binary (BinData) form. In a list of bits positions, the position of the least significant bit is 0.

## Example (MongoDB Shell)
<a name="bitsAnyClear-examples"></a>

The following example demonstrates how to use the `$bitsAnyClear` operator to check if any bit is clear in the `status` field of the `items` collection.

**Create sample documents**

```
db.items.insertMany([
  { "_id": 1, "status": 7 },
  { "_id": 2, "status": 15 },
  { "_id": 3, "status": 31 }
]);
```

**Query example**

```
db.items.find({ "status": { $bitsAnyClear: 8 } })
```

**Output**

```
{ "_id" : 1, "status" : 7 }
```

In this example, the query checks for documents where the `status` field has any bits clear (0) in the bitmask `8` (binary `1000`). The document with `status` values of `7` (binary `111`) matches the query, as it has at least one bit clear in the provided bitmask. The matching clear bit is the 4th least significant bit.

## Code examples
<a name="bitsAnyClear-code"></a>

To view a code example for using the `$bitsAnyClear` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('items');

  const result = await collection.find({ "status": { $bitsAnyClear: 8 } }).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.items

    result = list(collection.find({ "status": { "$bitsAnyClear": 8 } }))
    print(result)

    client.close()

example()
```

------

# \$1bitsAnySet
<a name="bitsAnySet"></a>

The `$bitsAnySet` operator in Amazon DocumentDB is used to query documents where at least one bit is set to 1 in the specified bits in a field. This operator allows you to perform bitwise operations on the values stored in fields, enabling efficient querying and analysis of data with bitwise characteristics.

**Parameters**
+ `field`: The field name to apply the bitwise operation to.
+ `value`: The numeric bitmask that specifies which bits should be checked, or a list of bits positions to be checked. A numeric bitmask can be a binary (0b...), decimal, hexadecimal (0x...), octal (0o...), or binary (BinData) form. In a list of bits positions, the position of the least significant bit is 0.

## Example (MongoDB Shell)
<a name="bitsAnySet-examples"></a>

The following example demonstrates how to use the `$bitsAnySet` operator to find documents where at least one bit is set in the `flags` field.

**Create sample documents**

```
db.collection.insertMany([
  { _id: 1, flags: 0b1010 },
  { _id: 2, flags: 0b1100 },
  { _id: 3, flags: 0b0011 },
  { _id: 4, flags: 0b0100 }
]);
```

**Query example**

```
db.collection.find({
  flags: { $bitsAnySet: 0b1010 }
})
```

**Output**

```
{ "_id" : 1, "flags" : 10 }
{ "_id" : 2, "flags" : 12 }
{ "_id" : 3, "flags" : 3 }
```

The query returns the documents where at least one of the bits specified in the bitmask `0b1010` is set in the `flags` field.

## Code examples
<a name="bitsAnySet-code"></a>

To view a code example for using the `$bitsAnySet` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.find({
    flags: { $bitsAnySet: 0b1010 }
  }).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['collection']

result = list(collection.find({
    'flags': { '$bitsAnySet': 0b1010 }
}))

print(result)

client.close()
```

------

# \$1comment
<a name="comment"></a>

The `$comment` operator in Amazon DocumentDB is used to attach a comment to a query. This can be useful for providing additional context or information about the query, which can be helpful for debugging or documenting purposes. The attached comment will appear as part of the output of operations like db.currentOp().

**Parameters**
+ `string`: The comment attached to the query.

## Example (MongoDB Shell)
<a name="comment-examples"></a>

The following example demonstrates how to use the `$comment` operator in Amazon DocumentDB.

**Create sample documents**

```
db.users.insertMany([
  { name: "John Doe", age: 30, email: "john.doe@example.com" },
  { name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
  { name: "Bob Johnson", age: 35, email: "bob.johnson@example.com" }
]);
```

**Query example**

```
db.users.find({ age: { $gt: 25 } }, { _id: 0, name: 1, age: 1 }).comment("Retrieve users older than 25");
```

**Output**

```
{ "name" : "John Doe", "age" : 30 }
{ "name" : "Bob Johnson", "age" : 35 }
```

## Code examples
<a name="comment-code"></a>

To view a code example for using the `$comment` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.find({ age: { $gt: 25 } }, { projection: { _id: 0, name: 1, age: 1 } })
                           .comment('Retrieve users older than 25')
                           .toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    users = db.users

    result = list(users.find({ 'age': { '$gt': 25 }}, { '_id': 0, 'name': 1, 'age': 1 })
                .comment('Retrieve users older than 25'))

    print(result)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1elemMatch
<a name="elemMatch"></a>

The `$elemMatch` operator in Amazon DocumentDB is used to query an array field and return documents where at least one element in the array matches the specified criteria. This operator is particularly useful when you have complex data structures with nested arrays or embedded documents.

Planner version 2.0 added index support for `$elemMatch`.

**Parameters**
+ `field`: The array field to query.
+ `query`: The criteria to match against the array elements.

 

**Using `$elemMatch` within an `$all` expression**

See [Using `$elemMatch` within an `$all` expression](functional-differences.md#functional-differences.elemMatch) for limitations regarding the use of the `$elemMatch` operator within an `$all` expression.

## Example (MongoDB Shell)
<a name="elemMatch-examples"></a>

The following example demonstrates how to use the `$elemMatch` operator to find documents where the `parts` array has at least one element that matches the specified criteria.

**Create sample documents**

```
db.col.insertMany([
  { _id: 1, parts: [{ part: "xyz", qty: 10 }, { part: "abc", qty: 20 }] },
  { _id: 2, parts: [{ part: "xyz", qty: 5 }, { part: "abc", qty: 10 }] },
  { _id: 3, parts: [{ part: "xyz", qty: 15 }, { part: "abc", qty: 100 }] },
  { _id: 4, parts: [{ part: "abc", qty: 150 }] }
]);
```

**Query example**

```
db.col.find({
  parts: { "$elemMatch": { part: "xyz", qty: { $lt: 11 } } }
})
```

**Output**

```
{ "_id" : 1, "parts" : [ { "part" : "xyz", "qty" : 10 }, { "part" : "abc", "qty" : 20 } ] }
{ "_id" : 2, "parts" : [ { "part" : "xyz", "qty" : 5 }, { "part" : "abc", "qty" : 10 } ] }
```

## Code examples
<a name="elemMatch-code"></a>

To view a code example for using the `$elemMatch` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const col = db.collection('col');

  const result = await col.find({
    parts: { 
      "$elemMatch": { part: "xyz", qty: { $lt: 11 } } 
    }
  }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    col = db['col']

    result = list(col.find({
      'parts': { 
        '$elemMatch': {'part': 'xyz', 'qty': {'$lt': 11}} 
      }
    }))

    print(result)
    client.close()

example()
```

------

# \$1eq
<a name="eq"></a>

The `$eq` operator in Amazon DocumentDB is used to match documents where the value of a field is equal to the specified value. This operator is commonly used in the `find()` method to retrieve documents that meet the specified criteria.

**Parameters**
+ `field` : The field to check for the equality condition.
+ `value` : The value to compare against the field.

## Example (MongoDB Shell)
<a name="eq-examples"></a>

The following example demonstrates the usage of the `$eq` operator to find all documents where the `name` field is equal to `"Thai Curry Palace"`.

**Create sample documents**

```
db.restaurants.insertMany([
  { name: "Thai Curry Palace", cuisine: "Thai", features: ["Private Dining"] },
  { name: "Italian Bistro", cuisine: "Italian", features: ["Outdoor Seating"] },
  { name: "Mexican Grill", cuisine: "Mexican", features: ["Takeout"] }
]);
```

**Query example**

```
db.restaurants.find({ name: { $eq: "Thai Curry Palace" } });
```

**Output**

```
{ "_id" : ObjectId("68ee586f916df9d39f3d9414"), "name" : "Thai Curry Palace", "cuisine" : "Thai", "features" : [ "Private Dining" ] }
```

## Code examples
<a name="eq-code"></a>

To view a code example for using the `$eq` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findByName(name) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('restaurants');

  const results = await collection.find({ name: { $eq: name } }).toArray();
  console.log(results);

  await client.close();
}

findByName("Thai Curry Palace");
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_by_name(name):
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    collection = db["restaurants"]

    results = list(collection.find({ "name": { "$eq": name } }))
    print(results)

    client.close()

find_by_name("Thai Curry Palace")
```

------

# \$1exists
<a name="exists"></a>

The `$exists` operator is used to check whether a field exists in a document or not. `$exists` particularly useful when working with sparse indexes in Amazon DocumentDB, where the indexed field may not be present in all documents.

To use a sparse index that you have created in a query, you must use the `$exists` clause on the fields that cover the index. If you omit `$exists`, Amazon DocumentDB will not use the sparse index for the query.

**Parameters**
+ `field`: The field name to check for existence.
+ `value`: A boolean value (`true` or `false`) that specifies whether the field should exist (`true`) or not exist (`false`) in the matching documents.

## Example (MongoDB Shell)
<a name="exists-examples"></a>

The following example demonstrates the use of the `$exists` operator with a sparse index on the `special_diets` field in the `food` collection.

**Create sample documents**

```
db.food.insertMany([
  { _id: 1, name: "Apple", special_diets: ["vegetarian", "gluten-free"] },
  { _id: 2, name: "Broccoli" },
  { _id: 3, name: "Chicken", special_diets: ["dairy-free"] }
]);
```

**Create a sparse index on the `special\$1diets` field**

```
db.food.createIndex({ "special_diets": 1 }, { sparse: true, name: "special_diets_sparse_asc" });
```

**Query example**

```
db.food.find({ "special_diets": { $exists: true } });
```

**Output**

```
[
  { "_id" : 1, "name" : "Apple", "special_diets" : [ "vegetarian", "gluten-free" ] },
  { "_id" : 3, "name" : "Chicken", "special_diets" : [ "dairy-free" ] }
]
```

## Code examples
<a name="exists-code"></a>

To view a code example for using the `$exists` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('food');

  const result = await collection.find({ "special_diets": { $exists: true } }).toArray();
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
import pymongo

client = pymongo.MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['food']

result = list(collection.find({"special_diets": {"$exists": True}}))
print(result)

client.close()
```

------

# \$1expr
<a name="expr"></a>

New from version 4.0.

Not supported by Elastic cluster.

The `$expr` operator in Amazon DocumentDB allows you to use aggregation expressions within the query language. It enables you to perform complex comparisons and computations on fields within a document, similar to the way you would use aggregation pipeline stages.

**Parameters**
+ `expression`: An expression that returns a boolean value, allowing you to perform comparisons and computations on document fields.

## Example (MongoDB Shell)
<a name="expr-examples"></a>

The following example demonstrates how to use the `$expr` operator to find all documents where the `manufacturingCost` field is greater than the `price` field.

**Create sample documents**

```
db.inventory.insertMany([
  { item: "abc", manufacturingCost: 500, price: 100 },
  { item: "def", manufacturingCost: 300, price: 450 },
  { item: "ghi", manufacturingCost: 400, price: 120 }
]);
```

**Query example**

```
db.inventory.find({
  $expr: {
    $gt: ["$manufacturingCost", "$price"]
  }
})
```

**Output**

```
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89a"), "item" : "abc", "manufacturingCost" : 500, "price" : 100 },
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89c"), "item" : "ghi", "manufacturingCost" : 400, "price" : 120 }
```

## Code examples
<a name="expr-code"></a>

To view a code example for using the `$expr` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.find({
    $expr: {
      $gt: ['$manufacturingCost', '$price']
    }
  }).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.find({
        '$expr': {
            '$gt': ['$manufacturingCost', '$price']
        }
    }))

    print(result)
    client.close()

example()
```

------

# \$1gt
<a name="gt"></a>

The `$gt` operator in Amazon DocumentDB is used to select documents where the value of the specified field is greater than the specified value. This operator is useful for filtering and querying data based on numerical comparisons.

**Parameters**
+ `field`: The field to compare.
+ `value`: The value to compare against.

## Example (MongoDB Shell)
<a name="gt-examples"></a>

The following example demonstrates how to use the `$gt` operator to find all documents where the `age` field is greater than 30.

**Create sample documents**

```
db.users.insertMany([
  { name: "John", age: 25 },
  { name: "Jane", age: 32 },
  { name: "Bob", age: 45 },
  { name: "Alice", age: 28 }
]);
```

**Query example**

```
db.users.find({ age: { $gt: 30 } });
```

**Output**

```
{ "_id" : ObjectId("6249e5c22a5d39884a0a0001"), "name" : "Jane", "age" : 32 },
{ "_id" : ObjectId("6249e5c22a5d39884a0a0002"), "name" : "Bob", "age" : 45 }
```

## Code examples
<a name="gt-code"></a>

To view a code example for using the `$gt` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findUsersOlderThan30() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = await db.collection('users').find({ age: { $gt: 30 } }).toArray();
  console.log(users);
  await client.close();
}

findUsersOlderThan30();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_users_older_than_30():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    users = list(db.users.find({ 'age': { '$gt': 30 } }))
    print(users)
    client.close()

find_users_older_than_30()
```

------

# \$1gte
<a name="gte"></a>

The `$gte` operator in Amazon DocumentDB is used to match values that are greater than or equal to a specified value. This operator is useful for filtering and querying data based on numerical comparisons.

**Parameters**
+ `field`: The field to check against the provided value.
+ `value`: The value to compare against the field.

## Example (MongoDB Shell)
<a name="gte-examples"></a>

The following example demonstrates the usage of the `$gte` operator in Amazon DocumentDB to find all documents where the "age" field is greater than or equal to 25.

**Create sample documents**

```
db.users.insertMany([
  { _id: 1, name: "John", age: 20 },
  { _id: 2, name: "Jane", age: 25 },
  { _id: 3, name: "Bob", age: 30 },
  { _id: 4, name: "Alice", age: 35 }
]);
```

**Query example**

```
db.users.find({ age: { $gte: 25 } }, { _id: 0, name: 1, age: 1 });
```

**Output**

```
{ "name" : "Jane", "age" : 25 }
{ "name" : "Bob", "age" : 30 }
{ "name" : "Alice", "age" : 35 }
```

## Code examples
<a name="gte-code"></a>

To view a code example for using the `$gte` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findUsersAboveAge(age) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.find({ age: { $gte: age } }, { projection: { _id: 0, name: 1, age: 1 } }).toArray();
  console.log(result);

  await client.close();
}

findUsersAboveAge(25);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_users_above_age(age):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    users = db.users

    result = list(users.find({ 'age': { '$gte': age } }, { '_id': 0, 'name': 1, 'age': 1 }))
    print(result)

    client.close()

find_users_above_age(25)
```

------

# \$1in
<a name="in"></a>

The `$in` operator in Amazon DocumentDB is a logical query operator that allows you to find documents where the value of a field equals any of the values specified in an array.

**Parameters**
+ `field`: The field to check against the provided array.
+ `[value1, value2, ...]`: An array of values to match against the specified field.

 

**Dollar (`$`) in field names**

See [Dollar(\$1) and dot(.) in field names](functional-differences.md#functional-differences-dollardot) for limitations regarding querying `$` prefixed fields in `$in` in nested objects.

## Example (MongoDB Shell)
<a name="in-examples"></a>

The following example demonstrates how to use the `$in` operator to find documents where the `color` field is one of the values in the provided array.

**Create sample documents**

```
db.colors.insertMany([
  { "_id": 1, "color": "red" },
  { "_id": 2, "color": "green" },
  { "_id": 3, "color": "blue" },
  { "_id": 4, "color": "yellow" },
  { "_id": 5, "color": "purple" }
])
```

**Query example**

```
db.colors.find({ "color": { "$in": ["red", "blue", "purple"] } })
```

**Output**

```
{ "_id": 1, "color": "red" },
{ "_id": 3, "color": "blue" },
{ "_id": 5, "color": "purple" }
```

## Code examples
<a name="in-code"></a>

To view a code example for using the `$in` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findByIn() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('colors');

  const result = await collection.find({ "color": { "$in": ["red", "blue", "purple"] } }).toArray();
  console.log(result);

  await client.close();
}

findByIn();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_by_in():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.colors

    result = list(collection.find({ "color": { "$in": ["red", "blue", "purple"] } }))
    print(result)

    client.close()

find_by_in()
```

------

# \$1jsonSchema
<a name="jsonSchema"></a>

New from version 4.0.

Not supported by Elastic cluster.

The `$jsonSchema` operator in Amazon DocumentDB is used to filter documents based on a specified JSON schema. This operator allows you to query documents that match a particular JSON schema, ensuring that the retrieved documents adhere to specific structural and data type requirements.

Using the `$jsonSchema` evaluation query operator as part of a collection creation, you can validate the schema of the documents being inserted into the collection. See [Using JSON schema validation](json-schema-validation.md) for additional information.

**Parameters**
+ `required` (array): Specifies the required fields in the document.
+ `properties` (object): Defines the data type and other constraints for each field in the document.

## Example (MongoDB Shell)
<a name="jsonSchema-examples"></a>

The following example demonstrates the use of the `$jsonSchema` operator to filter the `employees` collection to only retrieve documents that have the `name`, `employeeId` and `age` fields, and the `employeeId` field is of type `string`.

**Create sample documents**

```
db.employees.insertMany([
  { "name": { "firstName": "Carol", "lastName": "Smith" }, "employeeId": "1" },
  { "name": { "firstName": "Emily", "lastName": "Brown" }, "employeeId": "2", "age": 25 },
  { "name": { "firstName": "William", "lastName": "Taylor" }, "employeeId": 3, "age": 24 },
  { "name": { "firstName": "Jane", "lastName": "Doe" }, "employeeId": "4" }
]);
```

**Query example**

```
db.employees.aggregate([
  { $match: {
    $jsonSchema: {
      required: ["name", "employeeId", "age"],
      properties: { "employeeId": { "bsonType": "string" } }
    }
  }}
]);
```

**Output**

```
{ "_id" : ObjectId("6908e8b61f77fc26b2ecd26f"), "name" : { "firstName" : "Emily", "lastName" : "Brown" }, "employeeId" : "2", "age" : 25 }
```

## Code examples
<a name="jsonSchema-code"></a>

To view a code example for using the `$jsonSchema` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function filterByJsonSchema() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('employees');

  const result = await collection.aggregate([
    {
      $match: {
        $jsonSchema: {
          required: ['name', 'employeeId', 'age'],
          properties: { 'employeeId': { 'bsonType': 'string' } }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

filterByJsonSchema();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def filter_by_json_schema():
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
  db = client['test']
  collection = db['employees']

  result = list(collection.aggregate([
    {
      '$match': {
        '$jsonSchema': {
          'required': ['name', 'employeeId', 'age'],
          'properties': {'employeeId': {'bsonType': 'string'}}
        }
      }
    }
  ]))

  print(result)
  client.close()

filter_by_json_schema()
```

------

# \$1lt
<a name="lt"></a>

The `$lt` operator in Amazon DocumentDB is used to match values that are less than the specified value. This operator is useful for filtering and querying data based on numerical comparisons.

**Parameters**
+ `field`: The field name to check.
+ `value`: The value to compare against.

## Example (MongoDB Shell)
<a name="lt-examples"></a>

The following example demonstrates how to use the `$lt` operator to retrieve documents where the `Inventory.OnHand` value is less than 50.

**Create sample documents**

```
db.example.insertMany([
  { "_id": 1, "Inventory": { "OnHand": 25, "Sold": 60 }, "Colors": ["Red", "Blue"] },
  { "_id": 2, "Inventory": { "OnHand": 75, "Sold": 40 }, "Colors": ["Red", "White"] },
  { "_id": 3, "Inventory": { "OnHand": 10, "Sold": 85 }, "Colors": ["Red", "Green"] }
]);
```

**Query example**

```
db.example.find({ "Inventory.OnHand": { $lt: 50 } })
```

**Output**

```
{ "_id" : 1, "Inventory" : { "OnHand" : 25, "Sold" : 60 }, "Colors" : [ "Red", "Blue" ] }
{ "_id" : 3, "Inventory" : { "OnHand" : 10, "Sold" : 85 }, "Colors" : [ "Red", "Green" ] }
```

## Code examples
<a name="lt-code"></a>

To view a code example for using the `$lt` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  const result = await collection.find({ "Inventory.OnHand": { $lt: 50 } }).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    result = list(collection.find({ "Inventory.OnHand": { "$lt": 50 } }))
    print(result)

    client.close()

example()
```

------

# \$1mod
<a name="mod-query"></a>

The `$mod` query operator selects documents where a field value divided by a divisor has a specified remainder. This is useful for filtering documents based on modulo arithmetic conditions.

**Parameters**
+ `divisor`: The number to divide by.
+ `remainder`: The expected remainder value.

## Example (MongoDB Shell)
<a name="mod-query-examples"></a>

The following example demonstrates using the `$mod` operator to find all orders where the quantity is an odd number.

**Create sample documents**

```
db.orders.insertMany([
  { _id: 1, item: "Widget", quantity: 15 },
  { _id: 2, item: "Gadget", quantity: 20 },
  { _id: 3, item: "Tool", quantity: 7 },
  { _id: 4, item: "Device", quantity: 12 },
  { _id: 5, item: "Part", quantity: 9 }
]);
```

**Query example**

```
db.orders.find({ quantity: { $mod: [2, 1] } });
```

**Output**

```
{ "_id" : 1, "item" : "Widget", "quantity" : 15 }
{ "_id" : 3, "item" : "Tool", "quantity" : 7 }
{ "_id" : 5, "item" : "Part", "quantity" : 9 }
```

This query returns documents where the quantity divided by 2 has a remainder of 1, effectively selecting all odd quantities.

## Code examples
<a name="mod-query-code"></a>

To view a code example for using the `$mod` query operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.find({ quantity: { $mod: [2, 1] } }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.find({'quantity': {'$mod': [2, 1]}}))

    print(result)
    client.close()

example()
```

------

# \$1lte
<a name="lte"></a>

The `$lte` operator in Amazon DocumentDB is used to match documents where the value of a specified field is less than or equal to the specified value. This operator is useful for filtering and querying data based on numerical comparisons.

**Parameters**
+ `field`: The field to compare.
+ `value`: The value to compare against.

## Example (MongoDB Shell)
<a name="lte-examples"></a>

The following example demonstrates the usage of the `$lte` operator to retrieve documents where the `quantity` field is less than or equal to 10.

**Create sample documents**

```
db.inventory.insertMany([
  { item: "canvas", qty: 100 },
  { item: "paint", qty: 50 },
  { item: "brush", qty: 10 },
  { item: "paper", qty: 5 }
]);
```

**Query example**

```
db.inventory.find({ qty: { $lte: 10 } });
```

**Output**

```
{ "_id" : ObjectId("..."), "item" : "brush", "qty" : 10 },
{ "_id" : ObjectId("..."), "item" : "paper", "qty" : 5 }
```

## Code examples
<a name="lte-code"></a>

To view a code example for using the `$lte` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db("test");
  const collection = db.collection("inventory");

  const result = await collection.find({ qty: { $lte: 10 } }).toArray();
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client["test"]
    collection = db["inventory"]

    result = list(collection.find({ "qty": { "$lte": 10 } }))
    print(result)

    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1meta
<a name="meta"></a>

The `$meta` operator is used to access metadata associated with the current query execution. This operator is primarily used for text search operations, where the metadata can provide information about the relevance of the matched documents.

**Parameters**
+ `textScore`: Retrieves the text search score for the document. This score indicates the relevance of the document to the text search query.

## Example (MongoDB Shell)
<a name="meta-examples"></a>

The following example demonstrates how to use the `$meta` operator to retrieve the text search score for documents matching a text search query.

**Create sample documents**

```
db.documents.insertMany([
  { _id: 1, title: "Coffee Basics", content: "Coffee is a popular beverage made from roasted coffee beans." },
  { _id: 2, title: "Coffee Culture", content: "Coffee coffee coffee - the ultimate guide to coffee brewing and coffee preparation." },
  { _id: 3, title: "Tea vs Coffee", content: "Many people prefer tea over coffee for its health benefits." }
]);
```

**Create text index**

```
db.documents.createIndex({ content: "text" });
```

**Query example**

```
db.documents.find(
  { $text: { $search: "coffee" } },
  { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });
```

**Output**

```
[
  {
    title: 'Coffee Culture',
    content: 'Coffee coffee coffee - the ultimate guide to coffee brewing and coffee preparation.',
    score: 0.8897688388824463
  },
  {
    title: 'Coffee Basics',
    content: 'Coffee is a popular beverage made from roasted coffee beans.',
    score: 0.75990891456604
  },
  {
    title: 'Tea vs Coffee',
    content: 'Many people prefer tea over coffee for its health benefits.',
    score: 0.6079270839691162
  }
]
```

## Code examples
<a name="meta-code"></a>

To view a code example for using the `$meta` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findWithTextScore() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('documents');

  const result = await collection.find(
    { $text: { $search: "coffee" } },
    { projection: { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } } }
  ).sort({ score: { $meta: "textScore" } }).toArray();

  console.log(result);
  client.close();
}

findWithTextScore();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['documents']

for doc in collection.find(
    {'$text': {'$search': 'coffee'}},
    {'_id': 0, 'title': 1, 'content': 1, 'score': {'$meta': 'textScore'}}
).sort([('score', {'$meta': 'textScore'})]):
    print(doc)

client.close()
```

------

# \$1ne
<a name="ne"></a>

The `$ne` operator is used to match documents where the value of a field is not equal to the specified value. It is a comparison operator that can be used in query predicates to filter documents.

Planner version 2.0 added index support for `$ne`.

**Parameters**
+ `field`: The field to check.
+ `value`: The value to check against.

## Example (MongoDB Shell)
<a name="ne-examples"></a>

In this example, we'll find all documents in the `users` collection where the `status` field is not equal to `"active"`.

**Create sample documents**

```
db.users.insertMany([
  { name: "John", status: "active" },
  { name: "Jane", status: "inactive" },
  { name: "Bob", status: "suspended" },
  { name: "Alice", status: "active" }
]);
```

**Query example**

```
db.users.find({ status: { $ne: "active" } });
```

**Output**

```
[
  {
    _id: ObjectId('...'),
    name: 'Jane',
    status: 'inactive'
  },
  {
    _id: ObjectId('...'),
    name: 'Bob',
    status: 'suspended'
  }
]
```

## Code examples
<a name="ne-code"></a>

To view a code example for using the `$ne` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.find({ status: { $ne: 'active' } }).toArray();
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']

result = list(users.find({ 'status': { '$ne': 'active' } }))
print(result)

client.close()
```

------

# \$1nin
<a name="nin"></a>

The `$nin` operator is used to match values that are not in the specified array. It is the inverse of the `$in` operator, which matches values that are in the specified array.

Planner version 2.0 added index support for `$nin`.

**Parameters**
+ `field`: The field to check.
+ `array`: The array of values to check against.

 

**Dollar (`$`) in field names**

See [Dollar(\$1) and dot(.) in field names](functional-differences.md#functional-differences-dollardot) for limitations regarding querying `$` prefixed fields in `$nin` in nested objects.

## Example (MongoDB Shell)
<a name="nin-examples"></a>

The following example demonstrates how to use the `$nin` operator to find documents where the `category` field is not equal to "Fiction" or "Mystery".

**Create sample documents**

```
db.books.insertMany([
  { title: "The Great Gatsby", author: "F. Scott Fitzgerald", category: "Fiction" },
  { title: "To Kill a Mockingbird", author: "Harper Lee", category: "Fiction" },
  { title: "The Girl on the Train", author: "Paula Hawkins", category: "Mystery" },
  { title: "The Martian", author: "Andy Weir", category: "Science Fiction" },
  { title: "The Alchemist", author: "Paulo Coelho", category: "Philosophy" }
])
```

**Query example**

```
db.books.find({
  category: {
    $nin: ["Fiction", "Mystery"]
  }
})
```

**Output**

```
[
  {
    _id: ObjectId('...'),
    title: 'The Martian',
    author: 'Andy Weir',
    category: 'Science Fiction'
  },
  {
    _id: ObjectId('...'),
    title: 'The Alchemist',
    author: 'Paulo Coelho',
    category: 'Philosophy'
  }
]
```

## Code examples
<a name="nin-code"></a>

To view a code example for using the `$nin` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findBooksNotInCategories(categories) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const books = await db.collection('books').find({
    category: {
      $nin: categories
    }
  }).toArray();
  console.log(books);
  client.close();
}

findBooksNotInCategories(['Fiction', 'Mystery']);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_books_not_in_categories(categories):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    books = list(db.books.find({
        'category': {
            '$nin': categories
        }
    }))
    print(books)
    client.close()

find_books_not_in_categories(['Fiction', 'Mystery'])
```

------

# \$1nor
<a name="nor"></a>

The `$nor` operator is used to match documents where none of the specified query conditions are true. It is similar to the logical "NOR" operation, where the result is true if none of the operands are true.

**Parameters**
+ `expression1`: The first expression to evaluate.
+ `expression2`: The second expression to evaluate.
+ `expressionN`: Additional expressions to evaluate.

## Example (MongoDB Shell)
<a name="nor-examples"></a>

The following example demonstrates the usage of the `$nor` operator by retrieving documents where the `qty` field is not less than 20 and the `size` field is not equal to "XL".

**Create sample documents**

```
db.items.insertMany([
  { qty: 10, size: "M" },
  { qty: 15, size: "XL" },
  { qty: 25, size: "L" },
  { qty: 30, size: "XL" }
])
```

**Query example**

```
db.items.find({
  $nor: [
    { qty: { $lt: 20 } },
    { size: "XL" }
  ]
})
```

**Output**

```
[
  { "_id" : ObjectId("..."), "qty" : 25, "size" : "L" }
]
```

## Code examples
<a name="nor-code"></a>

To view a code example for using the `$nor` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('items');

  const result = await collection.find({
    $nor: [
      { qty: { $lt: 20 } },
      { size: "XL" }
    ]
  }).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['items']

    result = list(collection.find({
        '$nor': [
            { 'qty': { '$lt': 20 } },
            { 'size': 'XL' }
        ]
    }))

    print(result)

    client.close()

example()
```

------

# \$1not
<a name="not"></a>

The `$not` operator is used to negate the result of a given expression. It allows you to select documents where the specified condition does not match.

Planner version 2.0 added index support for `$not {eq}` and `$not {in}`.

**Parameters**
+ `expression`: The expression to negate.

## Example (MongoDB Shell)
<a name="not-examples"></a>

The following example demonstrates how to use the `$not` operator to find documents where the `status` field is not equal to "active".

**Create sample documents**

```
db.users.insertMany([
  { name: "John", status: "active" },
  { name: "Jane", status: "inactive" },
  { name: "Bob", status: "pending" },
  { name: "Alice", status: "active" }
]);
```

**Query example**

```
db.users.find({ status: { $not: { $eq: "active" } } });
```

**Output**

```
[
  {
    _id: ObjectId('...'),
    name: 'Jane',
    status: 'inactive'
  },
  {
    _id: ObjectId('...'),
    name: 'Bob',
    status: 'pending'
  }
]
```

## Code examples
<a name="not-code"></a>

To view a code example for using the `$not` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient, Filters } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.find({
    status: { $not: { $eq: "active" } }
  }).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from bson.son import SON

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['users']

result = collection.find({
    "status": {"$not": {"$eq": "active"}}
})

for doc in result:
    print(doc)

client.close()
```

------

# \$1or
<a name="or"></a>

The `$or` operator is used to perform a logical OR operation on an array of two or more expressions. It returns documents that match at least one of the expressions. This operator is useful when you need to query for documents that satisfy any one of multiple conditions.

**Parameters**
+ `expression1`: The first expression to evaluate.
+ `expression2`: The second expression to evaluate.
+ `...`: Additional expressions to evaluate (optional).

## Example (MongoDB Shell)
<a name="or-examples"></a>

The following example demonstrates the usage of the `$or` operator to find documents where the `make` is either "TruckForYou" with the model "Heavy H1" or "SportForYou" with the model "Bolid 1".

**Create sample documents**

```
db.cars.insertMany([
  { make: "TruckForYou", model: "Heavy H1", year: 2020 },
  { make: "SportForYou", model: "Bolid 1", year: 2021 },
  { make: "TruckForYou", model: "Cargo 5", year: 2019 },
  { make: "SportForYou", model: "Racer 2", year: 2022 }
]);
```

**Query example**

```
db.cars.find({
  $or: [
    { make: "TruckForYou", model: "Heavy H1" },
    { make: "SportForYou", model: "Bolid 1" }
  ]
});
```

**Output**

```
[
  {
    _id: ObjectId('...'),
    make: 'TruckForYou',
    model: 'Heavy H1',
    year: 2020
  },
  {
    _id: ObjectId('...'),
    make: 'SportForYou',
    model: 'Bolid 1',
    year: 2021
  }
]
```

## Code examples
<a name="or-code"></a>

To view a code example for using the `$or` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findCarsByMakeModel() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const cars = db.collection('cars');

  const result = await cars.find({
    $or: [
      { make: "TruckForYou", model: "Heavy H1" },
      { make: "SportForYou", model: "Bolid 1" }
    ]
  }).toArray();

  console.log(result);
  client.close();
}

findCarsByMakeModel();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_cars_by_make_model():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    cars = db.cars

    result = list(cars.find({
        '$or': [
            {'make': 'TruckForYou', 'model': 'Heavy H1'},
            {'make': 'SportForYou', 'model': 'Bolid 1'}
        ]
    }))

    print(result)
    client.close()

find_cars_by_make_model()
```

------

# \$1regex
<a name="regex"></a>

The `$regex` operator allows you to perform regular expression matching on string fields. It is a powerful tool for searching and filtering documents based on complex patterns.

**Parameters**
+ `regular expression`: The regular expression pattern to match against the field.
+ `$options`: (optional) Provides options to modify the search behavior, such as case-sensitivity, global matching, etc.

## Example (MongoDB Shell)
<a name="regex-examples"></a>

The following example demonstrates the usage of the `$regex` operator to search for documents where the "name" field matches a specific pattern.

**Create sample documents**

```
db.users.insertMany([
  { name: "John Doe" },
  { name: "Jane Smith" },
  { name: "Alice Johnson" },
  { name: "Bob Williams" },
  { name: "Charlie Davis" }
]);
```

**Query example**

```
db.users.find({ name: { $regex: /^A/ } })
```

**Output**

```
[
  { "_id" : ObjectId("..."), "name" : "Alice Johnson" }
]
```

This query will return all documents where the "name" field starts with the letter "A".

## Code examples
<a name="regex-code"></a>

To view a code example for using the `$regex` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const results = await collection.find({ name: { $regex: /^A/ } }).toArray();
  console.log(results);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    results = list(collection.find({ 'name': { '$regex': '^A' } }))
    print(results)

    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1slice
<a name="slice-projection"></a>

The `$slice` projection operator limits the number of array elements returned in a query result. It allows you to retrieve a specific number of elements from the start or end of an array field without loading the entire array.

**Parameters**
+ `field`: The array field to project.
+ `count`: Number of elements to return. Positive values return elements from the start, negative values from the end.

## Example (MongoDB Shell)
<a name="slice-projection-examples"></a>

The following example demonstrates how to use the `$slice` projection operator to return only the first two items from an array field.

**Create sample documents**

```
db.inventory.insertMany([
  { _id: 1, item: "notebook", tags: ["office", "school", "supplies", "writing"] },
  { _id: 2, item: "pen", tags: ["office", "writing"] },
  { _id: 3, item: "folder", tags: ["office", "supplies", "storage", "organization"] }
]);
```

**Query example**

```
db.inventory.find(
  {},
  { item: 1, tags: { $slice: 2 } }
)
```

**Output**

```
{ "_id" : 1, "item" : "notebook", "tags" : [ "office", "school" ] }
{ "_id" : 2, "item" : "pen", "tags" : [ "office", "writing" ] }
{ "_id" : 3, "item" : "folder", "tags" : [ "office", "supplies" ] }
```

## Code examples
<a name="slice-projection-code"></a>

To view a code example for using the `$slice` projection operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.find(
    {},
    { projection: { item: 1, tags: { $slice: 2 } } }
  ).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.find(
        {},
        {'item': 1, 'tags': {'$slice': 2}}
    ))

    print(result)
    client.close()

example()
```

------

# \$1size
<a name="size-query"></a>

The `$size` query operator matches documents where an array field has exactly the specified number of elements. This is useful for filtering documents based on array length.

**Parameters**
+ `field`: The array field to check.
+ `count`: The exact number of elements the array must contain.

## Example (MongoDB Shell)
<a name="size-query-examples"></a>

The following example demonstrates using the `$size` operator to find all products that have exactly three tags.

**Create sample documents**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", tags: ["electronics", "computers", "portable"] },
  { _id: 2, name: "Mouse", tags: ["electronics", "accessories"] },
  { _id: 3, name: "Desk", tags: ["furniture", "office", "workspace"] },
  { _id: 4, name: "Monitor", tags: ["electronics"] }
]);
```

**Query example**

```
db.products.find({ tags: { $size: 3 } });
```

**Output**

```
{ "_id" : 1, "name" : "Laptop", "tags" : [ "electronics", "computers", "portable" ] }
{ "_id" : 3, "name" : "Desk", "tags" : [ "furniture", "office", "workspace" ] }
```

## Code examples
<a name="size-query-code"></a>

To view a code example for using the `$size` query operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.find({ tags: { $size: 3 } }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.find({'tags': {'$size': 3}}))

    print(result)
    client.close()

example()
```

------

# \$1text
<a name="text"></a>

The `$text` operator is used to perform full-text search on text-indexed fields within a document collection. This operator allows you to search for documents that contain specific words or phrases, and can be combined with other query operators to filter results based on additional criteria.

**Parameters**
+ `$search`: The text string to search for.

## Example (MongoDB Shell)
<a name="text-examples"></a>

The following example demonstrates how to use the `$text` operator to search for documents containing the word "interest" and filter the results based on a "star\$1rating" field.

**Create sample documents**

```
db.test.insertMany([
  { "_id": 1, "star_rating": 4, "comments": "apple is red" },
  { "_id": 2, "star_rating": 5, "comments": "pie is delicious" },
  { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" },
  { "_id": 4, "star_rating": 2, "comments": "bake the apple pie in the oven" },
  { "_id": 5, "star_rating": 5, "comments": "interesting couch" },
  { "_id": 6, "star_rating": 5, "comments": "interested in couch for sale, year 2022" }
]);
```

**Create text index**

```
db.test.createIndex({ comments: "text" });
```

**Query example**

```
db.test.find({$and: [{star_rating: 5}, {$text: {$search: "interest"}}]})
```

**Output**

```
{ "_id" : 5, "star_rating" : 5, "comments" : "interesting couch" }
{ "_id" : 6, "star_rating" : 5, "comments" : "interested in couch for sale, year 2022" }
```

The command above returns documents with a text-indexed field containing any form of "interest" and a "star\$1rating" equal to 5.

## Code examples
<a name="text-code"></a>

To view a code example for using the `$text` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function searchDocuments() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('test');

  const result = await collection.find({
    $and: [
      { star_rating: 5 },
      { $text: { $search: 'interest' } }
    ]
  }).toArray();

  console.log(result);
  client.close();
}

searchDocuments();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def search_documents():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db.test

    result = list(collection.find({
        '$and': [
            {'star_rating': 5},
            {'$text': {'$search': 'interest'}}
        ]
    }))

    print(result)
    client.close()

search_documents()
```

------

# \$1type
<a name="type"></a>

The `$type` operator is used to check the data type of a field in a document. It can used when type-specific operations or validations are needed. The `$type` operator returns the BSON type of the evaluated expression. The returned type is a string, which corresponds to the type of the field or expression.

Planner version 2.0 added index support for `$type`.

**Parameters**
+ `expression` : The expression to evaluate.

## Example (MongoDB Shell)
<a name="type-examples"></a>

**Create sample documents**

```
db.documents.insertMany([
  { _id: 1, name: "John", age: 30, email: "john@example.com" },
  { _id: 2, name: "Jane", age: "25", email: 123456 },
  { _id: 3, name: 123, age: true, email: null }
]);
```

**Query example**

```
db.documents.find({
  $or: [
    { age: { $type: "number" } },
    { email: { $type: "string" } },
    { name: { $type: "string" } }
  ]
})
```

**Output**

```
[
  { "_id": 1, "name": "John", "age": 30, "email": "john@example.com" },
  { "_id": 2, "name": "Jane", "age": "25", "email": 123456 }
]
```

This query will return the documents where the `age` field is of type "number", the `email` field is of type "string", and the `name` field is of type "string".

## Code examples
<a name="type-code"></a>

To view a code example for using the `$type` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findByType() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('documents');

  const results = await collection.find({
    $or: [
      { age: { $type: 'number' } },
      { email: { $type: 'string' } },
      { name: { $type: 'string' } }
    ]
  }).toArray();

  console.log(results);
  client.close();
}

findByType();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_by_type():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['documents']

    results = list(collection.find({
        '$or': [
            {'age': {'$type': 'number'}},
            {'email': {'$type': 'string'}},
            {'name': {'$type': 'string'}}
        ]
    }))

    print(results)
    client.close()

find_by_type()
```

------

# Update operators
<a name="mongo-apis-update-operators"></a>

This section provides detailed information about update operators supported by Amazon DocumentDB.

**Topics**
+ [\$1](dollar-update.md)
+ [\$1[]](dollarBrackets-update.md)
+ [\$1[<identifier>]](dollarIdentifier-update.md)
+ [\$1addToSet](addToSet.md)
+ [\$1bit](bit.md)
+ [\$1currentDate](currentDate.md)
+ [\$1each](each.md)
+ [\$1inc](inc.md)
+ [\$1max](max-update.md)
+ [\$1min](min-update.md)
+ [\$1mul](mul.md)
+ [\$1pop](pop.md)
+ [\$1position](position.md)
+ [\$1pull](pull.md)
+ [\$1pullAll](pullAll.md)
+ [\$1push](push.md)
+ [\$1rename](rename.md)
+ [\$1set](set-update.md)
+ [\$1setOnInsert](setOnInsert.md)
+ [\$1slice](slice-update.md)
+ [\$1sort](sort-update.md)
+ [\$1unset](unset-update.md)

# \$1
<a name="dollar-update"></a>

The `$` positional operator updates the first array element that matches the query condition. It acts as a placeholder for the matched array element's position.

**Parameters**
+ `field.$`: The array field with the positional operator to update the first matching element.

## Example (MongoDB Shell)
<a name="dollar-update-examples"></a>

The following example demonstrates using the `$` positional operator to update a specific array element.

**Create sample documents**

```
db.inventory.insertMany([
  { _id: 1, item: "Widget", quantities: [10, 20, 30] },
  { _id: 2, item: "Gadget", quantities: [5, 15, 25] }
]);
```

**Query example**

```
db.inventory.updateOne(
  { _id: 1, quantities: 20 },
  { $set: { "quantities.$": 22 } }
);
```

**Output**

```
{
  "_id" : 1,
  "item" : "Widget",
  "quantities" : [ 10, 22, 30 ]
}
```

## Code examples
<a name="dollar-update-code"></a>

To view a code example for using the `$` positional operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  await collection.updateOne(
    { _id: 1, quantities: 20 },
    { $set: { "quantities.$": 22 } }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.inventory

    collection.update_one(
        {'_id': 1, 'quantities': 20},
        {'$set': {'quantities.$': 22}}
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1[]
<a name="dollarBrackets-update"></a>

The `$[]` all positional operator updates all elements in an array. It is used when you need to modify every element in an array field.

**Parameters**
+ `field.$[]`: The array field with the all positional operator to update all elements.

## Example (MongoDB Shell)
<a name="dollarBrackets-update-examples"></a>

The following example demonstrates using the `$[]` operator to update all array elements.

**Create sample documents**

```
db.products.insertOne({
  _id: 1,
  name: "Laptop",
  prices: [1000, 1100, 1200]
});
```

**Query example**

```
db.products.updateOne(
  { _id: 1 },
  { $inc: { "prices.$[]": 50 } }
);
```

**Output**

```
{
  "_id" : 1,
  "name" : "Laptop",
  "prices" : [ 1050, 1150, 1250 ]
}
```

## Code examples
<a name="dollarBrackets-update-code"></a>

To view a code example for using the `$[]` operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  await collection.updateOne(
    { _id: 1 },
    { $inc: { "prices.$[]": 50 } }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    collection.update_one(
        {'_id': 1},
        {'$inc': {'prices.$[]': 50}}
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1[<identifier>]
<a name="dollarIdentifier-update"></a>

The `$[<identifier>]` filtered positional operator updates all array elements that match the specified filter conditions. It is used with the `arrayFilters` option to selectively update array elements.

**Parameters**
+ `field.$[identifier]`: The array field with the filtered positional operator.
+ `arrayFilters`: An array of filter conditions that determine which elements to update.

## Example (MongoDB Shell)
<a name="dollarIdentifier-update-examples"></a>

The following example demonstrates using the `$[<identifier>]` operator to update specific array elements based on a condition.

**Create sample documents**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  grades: [
    { subject: "Math", score: 85 },
    { subject: "Science", score: 92 },
    { subject: "History", score: 78 }
  ]
});
```

**Query example**

```
db.students.updateOne(
  { _id: 1 },
  { $inc: { "grades.$[elem].score": 5 } },
  { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
);
```

**Output**

```
{
  "_id" : 1,
  "name" : "Alice",
  "grades" : [
    { "subject" : "Math", "score" : 90 },
    { "subject" : "Science", "score" : 97 },
    { "subject" : "History", "score" : 78 }
  ]
}
```

## Code examples
<a name="dollarIdentifier-update-code"></a>

To view a code example for using the `$[<identifier>]` operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  await collection.updateOne(
    { _id: 1 },
    { $inc: { "grades.$[elem].score": 5 } },
    { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.students

    collection.update_one(
        {'_id': 1},
        {'$inc': {'grades.$[elem].score': 5}},
        array_filters=[{'elem.score': {'$gte': 80}}]
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1addToSet
<a name="addToSet"></a>

The `$addToSet` operator in Amazon DocumentDB is used to add a value to an array only if the value is not already present in the array. This is useful for ensuring that an array contains unique elements.

**Parameters**
+ `field`: The field to update.
+ `value`: The value to add to the array field. This can be a single value or an expression.

## Example (MongoDB Shell)
<a name="addToSet-examples"></a>

The following example demonstrates how to use the `$addToSet` operator to add unique elements to an array.

**Create sample documents**

```
db.products.insertMany([
  { "_id": 1, "item": "apple", "tags": ["fruit", "red", "round"] },
  { "_id": 2, "item": "banana", "tags": ["fruit", "yellow"] },
  { "_id": 3, "item": "cherry", "tags": ["fruit", "red"] }
])
```

**Query example**

```
db.products.update(
  { "item": "apple" },
  { $addToSet: { "tags": "green" } }
)
```

**Output**

```
{ "_id": 1, "item": "apple", "tags": ["fruit", "red", "round", "green"] }
```

In this example, the `$addToSet` operator adds the "green" tag to the "tags" array of the document where the "item" field is "apple". Since "green" was not already in the array, it was added.

## Code examples
<a name="addToSet-code"></a>

To view a code example for using the `$addToSet` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  await collection.updateOne(
    { "item": "apple" },
    { $addToSet: { "tags": "green" } }
  );

  const updatedDoc = await collection.findOne({ "item": "apple" });
  console.log(updatedDoc);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    collection.update_one(
        {"item": "apple"},
        {"$addToSet": {"tags": "green"}}
    )

    updated_doc = collection.find_one({"item": "apple"})
    print(updated_doc)

    client.close()

example()
```

------

# \$1bit
<a name="bit"></a>

The `$bit` operator in Amazon DocumentDB allows you to perform bitwise operations on the bits of a given field. This can be useful for tasks like setting, clearing, or checking the state of individual bits within a number.

**Parameters**
+ `field`: The field to perform bitwise operations on.
+ `and`: An integer value that is used to perform a bitwise AND operation on the field.
+ `or`: An integer value that is used to perform a bitwise OR operation on the field.
+ `xor`: An integer value that is used to perform a bitwise XOR operation on the field.

## Example (MongoDB Shell)
<a name="bit-examples"></a>

The following example demonstrates how to use the `$bit` operator to perform bitwise operations on a numerical field.

**Create sample documents**

```
db.numbers.insert([
  { "_id": 1, "number": 5 },
  { "_id": 2, "number": 12 }
])
```

**Query example**

```
db.numbers.update(
  { "_id": 1 },
  { "$bit": { "number": { "and": 3 } } }
)
```

**Output**

```
{
  "_id": 1,
  "number": 1
}
```

In this example, the `$bit` operator is used to perform a bitwise AND operation on the "number" field of the document with the `_id` of 1. The result is that the value of the "number" field is set to 1, which is the result of the bitwise AND operation between the original value of 5 and the value 3.

## Code examples
<a name="bit-code"></a>

To view a code example for using the `$bit` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  await collection.updateOne(
    { "_id": 1 },
    { "$bit": { "number": { "and": 3 } } }
  );

  const result = await collection.findOne({ "_id": 1 });
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['numbers']

collection.update_one(
    {"_id": 1},
    {"$bit": {"number": {"and": 3}}}
)

result = collection.find_one({"_id": 1})
print(result)

client.close()
```

------

# \$1currentDate
<a name="currentDate"></a>

The `$currentDate` operator is used to set the value of a field to the current date and time. This operator is useful for automatically updating a field with the current timestamp when a document is inserted or updated.

**Parameters**
+ `field`: The field to update with the current date and time.
+ `type`: (optional) Specifies the BSON type to use for the current date. Can be either `date` or `timestamp`.

## Example (MongoDB Shell)
<a name="currentDate-examples"></a>

The following example demonstrates how to use the `$currentDate` operator to set the `lastModified` field to the current date and time when a new document is inserted.

**Create sample documents**

```
db.users.insert({
  name: "John Doe",
  email: "john.doe@example.com"
})
```

**Query example**

```
db.users.updateOne(
  { name: "John Doe" },
  { $currentDate: { lastModified: true } }
)
```

**View updated document**

```
db.users.findOne({ name: "John Doe" })
```

**Output**

```
{
  _id: ObjectId('...'),
  name: 'John Doe',
  email: 'john.doe@example.com',
  lastModified: ISODate('2025-10-25T22:50:29.963Z')
}
```

## Code examples
<a name="currentDate-code"></a>

To view a code example for using the `$currentDate` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateUserWithCurrentDate() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  await users.updateOne(
    { name: 'John Doe' },
    { $currentDate: { lastModified: true } }
  );

  console.log('User updated with current date');
  client.close();
}

updateUserWithCurrentDate();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_user_with_current_date():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db.users

    result = users.update_one(
        {'name': 'John Doe'},
        {'$currentDate': {'lastModified': True}}
    )

    print('User updated with current date')
    client.close()

update_user_with_current_date()
```

------

# \$1each
<a name="each"></a>

The `$each` operator is used in conjunction with other update operators, such as `$push` and `$addToSet`, to add multiple values to an array field. It allows adding multiple elements to an array in a single operation, rather than having to execute multiple update operations.

**Parameters**
+ `value`: The array of values to add to the array field.

## Example (MongoDB Shell)
<a name="each-examples"></a>

The following example demonstrates using the `$each` operator with the `$push` operator to add multiple elements to an array field.

**Create sample documents**

```
db.fruits.insertOne({
  _id: 1,
  fruits: ["apple", "banana"]
})
```

**Query example**

```
db.fruits.updateOne(
  { _id: 1 },
  { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
)
```

**View updated document**

```
db.fruits.findOne({ _id: 1 })
```

**Output**

```
{
  _id: 1,
  fruits: [ 'apple', 'banana', 'cherry', 'durian', 'elderberry' ]
}
```

## Code examples
<a name="each-code"></a>

To view a code example for using the `$each` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('fruits');

  await collection.updateOne(
    { _id: 1 },
    { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
  );

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['fruits']

    collection.update_one(
        {'_id': 1},
        {'$push': {'fruits': {'$each': ['cherry', 'durian', 'elderberry']}}}
    )

    client.close()

example()
```

------

# \$1inc
<a name="inc"></a>

The `$inc` operator is used to increment the value of a field by a specified amount. It is used to update a numeric field, such as a counter or a rating, without having to retrieve the current value, calculate the new value, and then update the field.

**Parameters**
+ `field`: The name of the field to increment.
+ `amount`: The amount by which to increment the field. This can be a positive or negative value.

## Example (MongoDB Shell)
<a name="inc-examples"></a>

The following example demonstrates how to use the `$inc` operator to increment the `age` field of a document.

**Create sample documents**

```
db.users.insertOne({_id: 123, name: "John Doe", age: 30})
```

**Query example**

```
db.users.updateOne({_id: 123}, {$inc: {age: 1}})
```

**View updated document**

```
db.users.findOne({_id: 123})
```

**Output**

```
{ "_id" : 123, "name" : "John Doe", "age" : 31 }
```

## Code examples
<a name="inc-code"></a>

To view a code example for using the `$inc` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateWithInc() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.updateOne(
    { _id: 123 },
    { $inc: { age: 1 } }
  );

  console.log(result);

  await client.close();
}

updateWithInc();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_with_inc():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    result = collection.update_one(
        {'_id': 123},
        {'$inc': {'age': 1}}
    )

    print(result.modified_count)

    client.close()

update_with_inc()
```

------

# \$1max
<a name="max-update"></a>

The `$max` update operator updates a field's value only if the specified value is greater than the current field value. This operator is useful for maintaining maximum values across updates.

**Parameters**
+ `field`: The field to update.
+ `value`: The value to compare with the current field value.

## Example (MongoDB Shell)
<a name="max-update-examples"></a>

The following example demonstrates using the `$max` operator to update the highest recorded score for a player.

**Create sample documents**

```
db.scores.insertMany([
  { _id: 1, player: "Alice", highScore: 85 },
  { _id: 2, player: "Bob", highScore: 92 },
  { _id: 3, player: "Charlie", highScore: 78 }
])
```

**Update example**

```
db.scores.updateOne(
  { _id: 1 },
  { $max: { highScore: 95 } }
)
```

**Result**

The `highScore` field for Alice is updated to 95 because 95 is greater than the current value of 85.

```
{ "_id": 1, "player": "Alice", "highScore": 95 }
```

## Code examples
<a name="max-update-code"></a>

To view a code example for using the `$max` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('scores');

  const result = await collection.updateOne(
    { _id: 1 },
    { $max: { highScore: 95 } }
  );

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['scores']

    result = collection.update_one(
        { '_id': 1 },
        { '$max': { 'highScore': 95 } }
    )

    print(result)
    client.close()

example()
```

------

# \$1min
<a name="min-update"></a>

The `$min` update operator updates a field's value only if the specified value is less than the current field value. This operator is useful for maintaining minimum values across updates.

**Parameters**
+ `field`: The field to update.
+ `value`: The value to compare with the current field value.

## Example (MongoDB Shell)
<a name="min-update-examples"></a>

The following example demonstrates using the `$min` operator to update the lowest recorded temperature for a weather station.

**Create sample documents**

```
db.weather.insertMany([
  { _id: 1, station: "Station A", lowestTemp: 15 },
  { _id: 2, station: "Station B", lowestTemp: 20 },
  { _id: 3, station: "Station C", lowestTemp: 18 }
])
```

**Update example**

```
db.weather.updateOne(
  { _id: 1 },
  { $min: { lowestTemp: 12 } }
)
```

**Result**

The `lowestTemp` field for Station A is updated to 12 because 12 is less than the current value of 15.

```
{ "_id": 1, "station": "Station A", "lowestTemp": 12 }
```

## Code examples
<a name="min-update-code"></a>

To view a code example for using the `$min` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('weather');

  const result = await collection.updateOne(
    { _id: 1 },
    { $min: { lowestTemp: 12 } }
  );

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['weather']

    result = collection.update_one(
        { '_id': 1 },
        { '$min': { 'lowestTemp': 12 } }
    )

    print(result)
    client.close()

example()
```

------

# \$1mul
<a name="mul"></a>

The `$mul` operator in Amazon DocumentDB is used to multiply the value of a field by a specified number. This can be useful for updating multiple documents atomically and consistently, such as updating flight miles based on a credit card status.

**Parameters**
+ `field`: The field to be multiplied.
+ `multiplier`: The number to multiply the field value by.

## Example (MongoDB Shell)
<a name="mul-examples"></a>

This example demonstrates how to use the `$mul` operator to double the `flight_miles` value for all documents where the `credit_card` field is `true`.

**Create sample documents**

```
db.miles.insertMany([
  { "_id": 1, "member_since": new Date("1987-01-01"), "credit_card": false, "flight_miles": [1205, 2560, 880] },
  { "_id": 2, "member_since": new Date("1982-01-01"), "credit_card": true, "flight_miles": [2410, 5120, 1780, 5560] },
  { "_id": 3, "member_since": new Date("1999-01-01"), "credit_card": true, "flight_miles": [2410, 1760] }
]);
```

**Query example**

```
db.miles.update(
  { "credit_card": { "$eq": true } },
  { "$mul": { "flight_miles.$[]": NumberInt(2) } },
  { "multi": true }
);
```

**Output**

```
{ "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ] }
{ "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 4820, 10240, 3560, 11120 ] }
{ "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 4820, 3520 ] }
```

For the customers that have a credit card, their flight miles have been doubled.

The `$[]` positional array operator is used to apply the `$mul` operation to each element in the `flight_miles` array.

## Code examples
<a name="mul-code"></a>

To view a code example for using the `$mul` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateFlightMiles() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  await collection.updateMany(
    { credit_card: true },
    { $mul: { 'flight_miles.$[]': 2 } }
  );

  const documents = await collection.find().toArray();
  console.log(documents);

  await client.close();
}

updateFlightMiles();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_flight_miles():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.miles

    collection.update_many(
        {'credit_card': True},
        {'$mul': {'flight_miles.$[]': 2}}
    )

    documents = list(collection.find())
    print(documents)

    client.close()

update_flight_miles()
```

------

# \$1pop
<a name="pop"></a>

The `$pop` operator in Amazon DocumentDB is used to remove the first or last element from an array field. It is particularly useful when you need to maintain a fixed-size array or implement a queue-like data structure within a document.

**Parameters**
+ `field`: The name of the array field to remove an element from.
+ `value`: An integer value that determines the position of the element to remove. A value of `1` removes the last element, while a value of `-1` removes the first element.

## Example (MongoDB Shell)
<a name="pop-examples"></a>

This example demonstrates how to use the `$pop` operator to remove the first and last elements from an array field.

**Create sample documents**

```
db.users.insertMany([
  { "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming", "hiking"] },
  { "_id": 2, "name": "Jane Smith", "hobbies": ["cooking", "gardening", "painting"] }
])
```

**Query example**

```
// Remove the first element from the "hobbies" array
db.users.update({ "_id": 1 }, { $pop: { "hobbies": -1 } })

// Remove the last element from the "hobbies" array
db.users.update({ "_id": 2 }, { $pop: { "hobbies": 1 } })
```

**Output**

```
{ "_id" : 1, "name" : "John Doe", "hobbies" : [ "swimming", "hiking" ] }
{ "_id" : 2, "name" : "Jane Smith", "hobbies" : [ "cooking", "gardening" ] }
```

## Code examples
<a name="pop-code"></a>

To view a code example for using the `$pop` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  // Remove the first element from the "hobbies" array
  await collection.updateOne({ "_id": 1 }, { $pop: { "hobbies": -1 } });

  // Remove the last element from the "hobbies" array
  await collection.updateOne({ "_id": 2 }, { $pop: { "hobbies": 1 } });

  const users = await collection.find().toArray();
  console.log(users);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    # Remove the first element from the "hobbies" array
    collection.update_one({"_id": 1}, {"$pop": {"hobbies": -1}})

    # Remove the last element from the "hobbies" array
    collection.update_one({"_id": 2}, {"$pop": {"hobbies": 1}})

    users = list(collection.find())
    print(users)

    client.close()

example()
```

------

# \$1position
<a name="position"></a>

The `$position` modifier in Amazon DocumentDB specifies the location in the array at which the `$push` operator inserts elements. Without the `$position` modifier, the `$push` operator inserts elements to the end of the array.

**Parameters**
+ `field`: The array field to update.
+ `num`: The position in the array where elements should be inserted, based on zero-based indexing.

**Note**: To use the `$position` modifier, it must appear with the `$each` modifier.

## Example (MongoDB Shell)
<a name="position-examples"></a>

The following example demonstrates how to use the `$position` operator to insert tasks at specific positions in a project management system.

**Create sample documents**

```
db.projects.insertOne({ "_id": 1, "name": "Website Redesign", "tasks": ["Design mockups"] })
```

**Query example 1 - Add urgent tasks at the beginning**

```
db.projects.updateOne(
   { _id: 1 },
   {
     $push: {
        tasks: {
           $each: ["Security audit", "Performance review"],
           $position: 0
        }
     }
   }
)
```

**Output 1**

```
{ "_id": 1, "name": "Website Redesign", "tasks": ["Security audit", "Performance review", "Design mockups"] }
```

**Query example 2 - Add tasks at specific position**

```
db.projects.insertOne({ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Deploy to store"] })

db.projects.updateOne(
   { _id: 2 },
   {
     $push: {
        tasks: {
           $each: ["Code review", "Testing phase"],
           $position: 2
        }
     }
   }
)
```

**Output 2**

```
{ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Code review", "Testing phase", "Deploy to store"] }
```

## Code examples
<a name="position-code"></a>

To view a code example for using the `$position` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function insertTasksAtPosition() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('projects');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        tasks: {
          $each: ["Security audit", "Performance review"],
          $position: 0
        }
      }
    }
  );

  const updatedProject = await collection.findOne({ _id: 1 });
  console.log(updatedProject);

  await client.close();
}

insertTasksAtPosition();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def insert_tasks_at_position():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['projects']

    result = collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'tasks': {
                    '$each': ['Security audit', 'Performance review'],
                    '$position': 0
                }
            }
        }
    )

    updated_project = collection.find_one({'_id': 1})
    print(updated_project)

    client.close()

insert_tasks_at_position()
```

------

# \$1pull
<a name="pull"></a>

The `$pull` operator is used to remove from an array all instances of a value or values that match a specified condition. This operator is useful when you need to remove specific elements from an array field within a document.

**Parameters**
+ `field`: The name of the array field from which to remove the value(s).
+ `value`: The value or condition that determines which element(s) to remove from the array.

## Example (MongoDB Shell)
<a name="pull-examples"></a>

The following example demonstrates how to use the `$pull` operator to remove elements from an array field.

**Create sample documents**

```
db.restaurants.insertMany([
  {
    name: "Pizza Hut",
    cuisine: "Italian",
    features: ["Delivery", "Takeout", "Dine-in"]
  },
  {
    name: "Sushi Saito",
    cuisine: "Japanese",
    features: ["Dine-in", "Private Dining"]
  },
  {
    name: "Taco Bell",
    cuisine: "Mexican",
    features: ["Delivery", "Takeout", "Drive-thru"]
  }
])
```

**Query example**

```
db.restaurants.updateMany(
  { cuisine: "Italian" },
  { $pull: { features: "Takeout" } }
)
```

**Output**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

The above query removes the "Takeout" feature from all documents where the `cuisine` field is "Italian".

## Code examples
<a name="pull-code"></a>

To view a code example for using the `$pull` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateRestaurants() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const restaurants = db.collection('restaurants');

  await restaurants.updateMany(
    { cuisine: 'Italian' },
    { $pull: { features: 'Takeout' } }
  );

  const updatedRestaurants = await restaurants.find({}).toArray();
  console.log(updatedRestaurants);

  await client.close();
}

updateRestaurants();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_restaurants():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    restaurants = db.restaurants

    result = restaurants.update_many(
        { 'cuisine': 'Italian' },
        { '$pull': { 'features': 'Takeout' } }
    )

    updated_restaurants = list(restaurants.find({}))
    print(updated_restaurants)

    client.close()

update_restaurants()
```

------

# \$1pullAll
<a name="pullAll"></a>

The `$pullAll` operator in Amazon DocumentDB is used to remove all instances of the specified values from an array field. This is particularly useful when you need to remove multiple elements from an array in a single operation.

**Parameters**
+ `field`: The name of the array field from which to remove the elements.
+ `value`: An array of values to remove from the array field.

## Example (MongoDB Shell)
<a name="pullAll-examples"></a>

The following example demonstrates how to use the `$pullAll` operator to remove multiple elements from an array field.

**Create sample documents**

```
db.restaurants.insert([
  {
    "name": "Taj Mahal",
    "cuisine": "Indian",
    "features": ["Private Dining", "Live Music"]
  },
  {
    "name": "Golden Palace",
    "cuisine": "Chinese",
    "features": ["Private Dining", "Takeout"]
  },
  {
    "name": "Olive Garden",
    "cuisine": "Italian",
    "features": ["Private Dining", "Outdoor Seating"]
  }
])
```

**Query example**

```
db.restaurants.update(
  { "name": "Taj Mahal" },
  { $pullAll: { "features": ["Private Dining", "Live Music"] } }
)
```

**Output**

```
{
  "name": "Taj Mahal",
  "cuisine": "Indian",
  "features": []
}
```

## Code examples
<a name="pullAll-code"></a>

To view a code example for using the `$pullAll` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('restaurants');

  await collection.updateMany(
    { "name": "Taj Mahal" },
    { $pullAll: { "features": ["Private Dining", "Live Music"] } }
  );

  const updatedDocument = await collection.findOne({ "name": "Taj Mahal" });
  console.log(updatedDocument);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['restaurants']

    collection.update_many(
        {"name": "Taj Mahal"},
        {"$pullAll": {"features": ["Private Dining", "Live Music"]}}
    )

    updated_document = collection.find_one({"name": "Taj Mahal"})
    print(updated_document)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1push
<a name="push"></a>

The `$push` operator in Amazon DocumentDB is used to add an item to an array field in a document. This operator is particularly useful when you need to append new data to an existing array without overwriting the entire array.

**Parameters**
+ `field`: The name of the array field to which the new element should be added.
+ `value`: The value to be added to the array.
+ `position`: (optional) A modifier that specifies the position in the array where the new element should be added. Supported modifiers include `$` (add to the end of the array) and `$[]` (add to the end of the array, ignoring any array filters).

## Example (MongoDB Shell)
<a name="push-examples"></a>

The following example demonstrates how to use the `$push` operator to add new elements to an array field in a document.

**Create sample documents**

```
db.users.insert([
  { _id: 1, name: "John Doe", hobbies: ["reading", "swimming"] },
  { _id: 2, name: "Jane Smith", hobbies: ["gardening", "cooking"] }
])
```

**Query example**

```
db.users.updateOne(
  { _id: 1 },
  { $push: { hobbies: "hiking" } }
)
```

**Output**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

After running the update, the document with `_id: 1` will have the `hobbies` array updated to `[&quot;reading&quot;, &quot;swimming&quot;, &quot;hiking&quot;]`.

## Code examples
<a name="push-code"></a>

To view a code example for using the `$push` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.updateOne(
    { _id: 1 },
    { $push: { hobbies: "hiking" } }
  );

  console.log(result);
  client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    result = collection.update_one(
        {'_id': 1},
        {'$push': {'hobbies': 'hiking'}}
    )

    print(result.raw_result)
    client.close()

update_document()
```

------

# \$1rename
<a name="rename"></a>

The `$rename` operator in Amazon DocumentDB is used to rename a field in a document. This operator can be particularly useful when you need to update the structure of your documents or align them with new data models.

**Parameters**
+ `field`: The field to be renamed.
+ `newName`: The new name for the field.

## Example (MongoDB Shell)
<a name="rename-examples"></a>

The following example demonstrates how to use the `$rename` operator to rename the `&quot;Date.DoW&quot;` field to `&quot;Date.DayOfWeek&quot;` in a document with the `&quot;DocName&quot;` field set to `&quot;Document 1&quot;`.

**Create sample documents**

```
db.example.insertOne({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**Query example**

```
db.example.update(
    { "DocName": "Document 1" },
    { $rename: { "Date.DoW": "Date.DayOfWeek" } }
)
```

**Output**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DayOfWeek": "Saturday"
    },
    "Words": 2482
}
```

## Code examples
<a name="rename-code"></a>

To view a code example for using the `$rename` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
    const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
    const db = client.db('test');
    const collection = db.collection('example');

    await collection.updateOne(
        { "DocName": "Document 1" },
        { $rename: { "Date.DoW": "Date.DayOfWeek" } }
    );

    const updatedDoc = await collection.findOne({ "DocName": "Document 1" });
    console.log(updatedDoc);

    await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    collection.update_one(
        {"DocName": "Document 1"},
        {"$rename": {"Date.DoW": "Date.DayOfWeek"}}
    )

    updated_doc = collection.find_one({"DocName": "Document 1"})
    print(updated_doc)

    client.close()

example()
```

------

# \$1set
<a name="set-update"></a>

The `$set` operator in Amazon DocumentDB is used to update the value of a specified field in a document. This operator allows you to add new fields or modify existing ones within a document. It is a fundamental update operator in the MongoDB Java driver, which is compatible with Amazon DocumentDB.

**Parameters**
+ `field`: The field to update.
+ `value`: The new value for the field.

## Example (MongoDB Shell)
<a name="set-examples"></a>

The following example demonstrates how to use the `$set` operator to update the `Item` field in a document.

**Create sample documents**

```
db.example.insert([
  {
    "Item": "Pen",
    "Colors": ["Red", "Green", "Blue", "Black"],
    "Inventory": {
      "OnHand": 244,
      "MinOnHand": 72
    }
  },
  {
    "Item": "Poster Paint",
    "Colors": ["Red", "Green", "Blue", "White"],
    "Inventory": {
      "OnHand": 120,
      "MinOnHand": 36
    }
  }
])
```

**Query example**

```
db.example.update(
  { "Item": "Pen" },
  { $set: { "Item": "Gel Pen" } }
)
```

**Output**

```
{
  "Item": "Gel Pen",
  "Colors": ["Red", "Green", "Blue", "Black"],
  "Inventory": {
    "OnHand": 244,
    "MinOnHand": 72
  }
}
```

## Code examples
<a name="set-code"></a>

To view a code example for using the `$set` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  await collection.updateOne(
    { "Item": "Pen" },
    { $set: { "Item": "Gel Pen" } }
  );

  const updatedDocument = await collection.findOne({ "Item": "Gel Pen" });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.example

    collection.update_one(
        {"Item": "Pen"},
        {"$set": {"Item": "Gel Pen"}}
    )

    updated_document = collection.find_one({"Item": "Gel Pen"})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1setOnInsert
<a name="setOnInsert"></a>

The `$setOnInsert` operator in Amazon DocumentDB is used to set the value of a field if a document is being inserted, but it has no effect if the document is being updated.

**Parameters**
+ `field`: The field to be set.
+ `value`: The value to assign to the field.

## Example (MongoDB Shell)
<a name="setOnInsert-examples"></a>

The following example demonstrates the usage of the `$setOnInsert` operator in Amazon DocumentDB. It creates a new document if the document does not already exist, but it has no effect if the document is being updated.

**Create sample documents**

```
db.users.insertOne({
  _id: 1,
  name: "John Doe",
  age: 30
})
```

**Query example 1 - Update existing document**

```
db.users.update(
  { _id: 1 },
  {
    $set: { age: 31 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**Output 1**

```
{
  _id: 1,
  name: "John Doe",
  age: 31
}
```

The output shows that the document was updated, but the `createdAt` field was **NOT added** since the document already existed. The `$setOnInsert` operator only applies when inserting new documents.

**Query example 2 - Insert new document (upsert)**

```
db.users.update(
  { _id: 2 },
  {
    $set: { name: "Jane Smith", age: 25 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**Output 2**

```
{
  _id: 2,
  name: "Jane Smith", 
  age: 25,
  createdAt: ISODate("2025-10-31T09:57:52.459Z")
}
}
```

## Code examples
<a name="setOnInsert-code"></a>

To view a code example for using the `$setOnInsert` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateWithSetOnInsert() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  await users.updateOne(
    { _id: 1 },
    {
      $set: { age: 31 },
      $setOnInsert: { createdAt: new Date() }
    },
    { upsert: true }
  );

  const updatedUser = await users.findOne({ _id: 1 });
  console.log(updatedUser);

  await client.close();
}

updateWithSetOnInsert();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_with_set_on_insert():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = users.update_one(
        {'_id': 1},
        {
            '$set': {'age': 31},
            '$setOnInsert': {'createdAt': datetime.datetime.now()}
        },
        upsert=True
    )

    updated_user = users.find_one({'_id': 1})
    print(updated_user)

    client.close()

update_with_set_on_insert()
```

------

# \$1slice
<a name="slice-update"></a>

The `$slice` update operator modifies an array by limiting its size. When used with the `$push` operator, it restricts the number of elements in an array, keeping only the specified number of most recent or oldest elements.

**Parameters**
+ `field`: The array field to modify.
+ `count`: Maximum number of elements to keep. Positive values keep the first N elements, negative values keep the last N elements.

## Example (MongoDB Shell)
<a name="slice-update-examples"></a>

The following example demonstrates how to use the `$slice` update operator with `$push` to maintain a fixed-size array of recent scores.

**Create sample documents**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  scores: [85, 90, 78]
});
```

**Query example**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      scores: {
        $each: [92, 88],
        $slice: -3
      }
    }
  }
)
```

**Output**

```
{
  "_id" : 1,
  "name" : "Alice",
  "scores" : [ 78, 92, 88 ]
}
```

In this example, the `$slice: -3` modifier keeps only the last three elements after pushing new values to the array.

## Code examples
<a name="slice-update-code"></a>

To view a code example for using the `$slice` update operator, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        scores: {
          $each: [92, 88],
          $slice: -3
        }
      }
    }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.students

    collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'scores': {
                    '$each': [92, 88],
                    '$slice': -3
                }
            }
        }
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1sort
<a name="sort-update"></a>

The `$sort` update modifier orders array elements when used with the `$push` operator. It arranges array elements in ascending or descending order based on specified field values or the elements themselves.

**Parameters**
+ `field`: The array field to modify.
+ `order`: Use `1` for ascending order or `-1` for descending order.

## Example (MongoDB Shell)
<a name="sort-update-examples"></a>

The following example demonstrates using the `$sort` modifier with `$push` to add new quiz scores and keep them sorted in descending order.

**Create sample documents**

```
db.students.insertOne({
  _id: 1,
  name: "Bob",
  quizzes: [
    { score: 85, date: "2024-01-15" },
    { score: 92, date: "2024-02-10" }
  ]
});
```

**Query example**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      quizzes: {
        $each: [{ score: 78, date: "2024-03-05" }],
        $sort: { score: -1 }
      }
    }
  }
)
```

**Output**

```
{
  "_id" : 1,
  "name" : "Bob",
  "quizzes" : [
    { "score" : 92, "date" : "2024-02-10" },
    { "score" : 85, "date" : "2024-01-15" },
    { "score" : 78, "date" : "2024-03-05" }
  ]
}
```

## Code examples
<a name="sort-update-code"></a>

To view a code example for using the `$sort` update modifier, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        quizzes: {
          $each: [{ score: 78, date: "2024-03-05" }],
          $sort: { score: -1 }
        }
      }
    }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.students

    collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'quizzes': {
                    '$each': [{'score': 78, 'date': '2024-03-05'}],
                    '$sort': {'score': -1}
                }
            }
        }
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1unset
<a name="unset-update"></a>

The `$unset` operator in Amazon DocumentDB is used to remove a specified field from a document. When a field is removed using `$unset`, the field is deleted from the document, and the document size is reduced accordingly. This can be useful when you want to remove unnecessary data from your documents.

**Parameters**
+ `field`: The field to remove from the document. This can be a single field or a dotted path to a nested field.

## Example (MongoDB Shell)
<a name="unset-examples"></a>

The following example demonstrates how to use the `$unset` operator to remove the `Words` field from a document in the `example` collection.

**Create sample documents**

```
db.example.insert({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**Query example**

```
db.example.update(
    { "DocName" : "Document 1" },
    { $unset: { Words:1 } }
)
```

**Output**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    }
}
```

In this example, the `$unset` operator is used to remove the `Words` field from the document with `DocName` equal to "Document 1". The resulting document no longer contains the `Words` field.

## Code examples
<a name="unset-code"></a>

To view a code example for using the `$unset` command, choose the tab for the language that you want to use:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function removeField() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  const result = await collection.updateOne(
    { "DocName": "Document 1" },
    { $unset: { "Words": 1 } }
  );

  console.log(`Modified ${result.modifiedCount} document(s)`);
  client.close();
}

removeField();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def remove_field():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    result = collection.update_one(
        {"DocName": "Document 1"},
        {"$unset": {"Words": 1}}
    )

    print(f"Modified {result.modified_count} document(s)")
    client.close()

remove_field()
```

------