

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 在 Amazon Document APIs DB 中支持 MongoDB、操作和数据类型
<a name="mongo-apis"></a>

Amazon DocumentDB（与 MongoDB 兼容）是一个快速、可扩展、高度可用且完全托管的文档数据库服务，它支持 MongoDB 工作负载。亚马逊 DocumentDB 与 MongoDB 3.6、4.0、5.0 和 8.0 兼容。 APIs本部分列出了支持的功能。要获得使用 M APIs ongoDB 和驱动程序的支持，请查阅 MongoDB 社区论坛。如需使用亚马逊 DocumentDB 服务的支持，请联系相应的 AWS 支持团队。有关 Amazon DocumentDB 和 MongoDB 之间的功能差异，请参阅 [功能差异：Amazon DocumentDB 和 MongoDB](functional-differences.md)。

仅供内部使用或不适用于完全托管的服务的 MongoDB 命令和运算符不受支持，并且未包含在支持的功能列表中。

自发布以来，我们已添加 50 多种附加功能，并将继续向客户学习以提供他们所需的功能。有关最近发布的信息，请参阅 [Amazon DocumentDB 公告](https://aws.amazon.com/documentdb/resources/)。

如果您希望我们构建一项不受支持的功能，请向 [Amazon DocumentDB 服务团队](mailto:documentdb-feature-request@amazon.com)发送一封包含您的 accountID、请求的功能和使用案例的电子邮件来告知我们此情况。
+ [数据库命令](#mongo-apis-database)
+ [查询和投影运算符](#mongo-apis-query)
+ [更新运算符](#mongo-apis-update)
+ [地理空间](#mongo-apis-geospatial)
+ [游标方法](#mongo-apis-cursor)
+ [聚合管道运算符](#mongo-apis-aggregation-pipeline)
+ [数据类型](#mongo-apis-data-types)
+ [索引](#mongo-apis-indexes)

## 数据库命令
<a name="mongo-apis-database"></a>

**Topics**
+ [管理命令](#mongo-apis-dababase-administrative)
+ [聚合](#mongo-apis-dababase-aggregation)
+ [身份验证](#mongo-apis-dababase-authentication)
+ [诊断命令](#mongo-apis-dababase-diagnostics)
+ [查询和写入操作](#mongo-apis-dababase-query-write)
+ [角色管理命令](#mongo-apis-database-role-management)
+ [会话命令](#mongo-apis-dababase-sessions)
+ [User management](#mongo-apis-dababase-user-management)
+ [分片命令](#mongo-apis-dababase-sharding)

### 管理命令
<a name="mongo-apis-dababase-administrative"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  受限集合  |  否  |  否  |  否  |  否  |  否  | 
|  cloneCollectionAs已封顶  |  否  |  否  |  否  |  否  |  否  | 
|  collMod  |  部分  |  部分  |  部分  |  部分  |  部分  | 
|  collMod： expireAfterSeconds  |  支持  |  是  |  是  |  是  |  是  | 
|  convertToCapped  |  否  |  否  |  否  |  否  |  否  | 
|  copydb  |  否  |  否  |  否  |  否  |  否  | 
|  创建  |  支持  |  是  |  是  |  是  |  是  | 
|  createView  |  否  |  否  |  否  |  是  |  否  | 
|  createIndexes  |  支持  |  是  |  是  |  是  |  是  | 
|  currentOp  |  支持  |  是  |  是  |  是  |  是  | 
|  drop  |  支持  |  是  |  是  |  是  |  是  | 
|  dropDatabase  |  支持  |  是  |  是  |  是  |  是  | 
|  dropIndexes  |  支持  |  是  |  是  |  是  |  是  | 
|  filemd5  |  否  |  否  |  否  |  否  |  否  | 
|  getAuditConfig  |  否  |  是  |  是  |  是  |  否  | 
|  killCursors  |  支持  |  是  |  是  |  是  |  是  | 
|  killOp  |  支持  |  是  |  是  |  是  |  是  | 
|  listCollections\$1  |  支持  |  是  |  是  |  是  |  是  | 
|  listDatabases  |  支持  |  是  |  是  |  是  |  是  | 
|  listIndexes  |  支持  |  是  |  是  |  是  |  是  | 
|  reIndex  |  否  |  否  |  是  |  是  |  否  | 
|  renameCollection  |  支持  |  是  |  是  |  是  |  否  | 
|  setAuditConfig  |  否  |  是  |  是  |  是  |  否  | 

\$1 不支持筛选选项中的 `type` 密钥。

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


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  aggregate  |  支持  |  是  |  是  |  是  |  是  | 
|  count  |  支持  |  是  |  是  |  是  |  是  | 
|  区分  |  支持  |  是  |  是  |  是  |  是  | 
|  mapReduce  |  否  |  否  |  否  |  是  |  否  | 

### 身份验证
<a name="mongo-apis-dababase-authentication"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  authenticate  |  支持  |  是  |  是  |  是  |  是  | 
|  注销  |  支持  |  是  |  是  |  是  |  是  | 

### 诊断命令
<a name="mongo-apis-dababase-diagnostics"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  buildInfo  |  支持  |  是  |  是  |  是  |  是  | 
|  collStats  |  支持  |  是  |  是  |  是  |  是  | 
|  connPoolStats  |  否  |  否  |  否  |  否  |  否  | 
|  connectionStatus  |  支持  |  是  |  是  |  是  |  是  | 
|  dataSize  |  支持  |  是  |  是  |  是  |  是  | 
|  dbHash  |  否  |  否  |  否  |  否  |  否  | 
|  dbStats  |  支持  |  是  |  是  |  是  |  是  | 
|  explain  |  支持  |  是  |  是  |  是  |  是  | 
|  解释：executionStats  |  支持  |  是  |  是  |  是  |  是  | 
|  功能  |  否  |  否  |  否  |  否  |  否  | 
|  hostInfo  |  支持  |  是  |  是  |  是  |  是  | 
|  listCommands  |  支持  |  是  |  是  |  是  |  是  | 
|  profiler  |  [是](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [是](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [是](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [是](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  否  | 
|  serverStatus  |  支持  |  是  |  是  |  是  |  是  | 
|  top  |  支持  |  是  |  是  |  是  |  是  | 

### 查询和写入操作
<a name="mongo-apis-dababase-query-write"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  变更流  |  [是](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [是](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [是](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [是](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  否  | 
|  删除  |  支持  |  是  |  是  |  是  |  是  | 
|  查找  |  支持  |  是  |  是  |  是  |  是  | 
|  findAndModify  |  是  |  是  |  是  |  是  |  是  | 
|  getLastError  |  否  |  否  |  否  |  否  |  否  | 
|  getMore  |  支持  |  是  |  是  |  是  |  是  | 
|  getPrevError  |  否  |  否  |  否  |  否  |  否  | 
|  GridFS  |  支持  |  是  |  是  |  是  |  否  | 
|  insert  |  支持  |  是  |  是  |  是  |  是  | 
|  parallelCollectionScan  |  否  |  否  |  否  |  否  |  否  | 
|  resetError  |  否  |  否  |  否  |  否  |  否  | 
|  更新  |  支持  |  是  |  是  |  是  |  是  | 
|  ReplaceOne  |  是  |  是  |  是  |  是  |  是  | 

### 角色管理命令
<a name="mongo-apis-database-role-management"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  createRole  |  支持  |  是  |  是  |  是  |  否  | 
|  dropAllRolesFromDatabase  |  是  |  是  |  是  |  是  |  否  | 
|  dropRole  |  支持  |  是  |  是  |  是  |  否  | 
|  grantRolesTo角色  |  支持  |  是  |  是  |  是  |  否  | 
|  revokeRolesFrom角色  |  支持  |  是  |  是  |  是  |  否  | 
|  revokePrivilegesFrom角色  |  支持  |  是  |  是  |  是  |  否  | 
|  rolesInfo  |  支持  |  是  |  是  |  是  |  否  | 
|  updateRole  |  支持  |  是  |  是  |  是  |  否  | 

### 会话命令
<a name="mongo-apis-dababase-sessions"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  abortTransaction  |  否  |  是  |  是  |  是  |  否  | 
|  commitTransaction  |  否  |  是  |  是  |  是  |  否  | 
|  endSessions  |  否  |  否  |  否  |  否  |  否  | 
|   killAllSessions  |  否  |  是  |  是  |  是  |  否  | 
|  killAllSessionsByPattern  |  否  |  否  |  否  |  否  |  否  | 
|  killSessions  |  否  |  是  |  是  |  是  |  否  | 
|  refreshSessions  |  否  |  否  |  否  |  否  |  否  | 
|  startSession  |  否  |  是  |  是  |  是  |  否  | 

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


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  createUser  |  支持  |  是  |  是  |  是  |  是  | 
|  dropAllUsersFromDatabase  |  是  |  是  |  是  |  是  |  是  | 
|  dropUser  |  支持  |  是  |  是  |  是  |  是  | 
|  grantRolesToUser  |  是  |  是  |  是  |  是  |  是  | 
|  revokeRolesFromUser  |  是  |  是  |  是  |  是  |  是  | 
|  updateUser  |  支持  |  是  |  是  |  是  |  是  | 
|  usersInfo  |  支持  |  是  |  是  |  是  |  是  | 

### 分片命令
<a name="mongo-apis-dababase-sharding"></a>


| 命令 | 弹性集群 | 
| --- | --- | 
|  abortReshardCollection  |  否  | 
|  addShard  |  否  | 
|  addShardTo区域  |  否  | 
|  balancerCollectionStatus  |  否  | 
|  balancerStart  |  否  | 
|  balancerStatus  |  否  | 
|  balancerStop  |  否  | 
|  checkShardingIndex  |  否  | 
|  clearJumboFlag  |  否  | 
|  cleanupOrphaned  |  否  | 
|  cleanupReshardCollection  |  否  | 
|  commitReshardCollection  |  否  | 
|  enableSharding  |  是  | 
|  flushRouterConfig  |  否  | 
|  getShardMap  |  否  | 
|  getShardVersion  |  否  | 
|  isdbgrid  |  否  | 
|  listShards  |  否  | 
|  medianKey  |  否  | 
|  moveChunk  |  否  | 
|  movePrimary  |  否  | 
|  mergeChunks  |  否  | 
|  refineCollectionShard钥匙  |  否  | 
|  removeShard  |  否  | 
|  removeShardFrom区域  |  否  | 
|  reshardCollection  |  否  | 
|  setAllowMigrations  |  否  | 
|  setShardVersion  |  否  | 
|  shardCollection  |  是  | 
|  shardingState  |  否  | 
|  split  |  否  | 
|  splitVector  |  否  | 
|  unsetSharding  |  否  | 
|  updateZoneKey射程  |  否  | 

## 查询和投影运算符
<a name="mongo-apis-query"></a>

**Topics**
+ [数组运算符](#mongo-apis-query-array-operators)
+ [按位运算符](#mongo-apis-query-bitwise-operators)
+ [注释运算符](#mongo-apis-query-comment-operator)
+ [比较运算符](#mongo-apis-query-comparison-operators)
+ [元素运算符](#mongo-apis-query-element-operators)
+ [评估查询运算符](#mongo-apis-query-evaluation-operators)
+ [逻辑运算符](#mongo-apis-query-logical-operators)
+ [投影运算符](#mongo-apis-projection-operators)

### 数组运算符
<a name="mongo-apis-query-array-operators"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1all](all.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1elemMatch](elemMatch.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1size](size-query.md)  |  是  |  是  |  是  |  是  |  是  | 

### 按位运算符
<a name="mongo-apis-query-bitwise-operators"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1bitsAllSet](bitsAllSet.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1bitsAnySet](bitsAnySet.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1bitsAllClear](bitsAllClear.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1bitsAnyClear](bitsAnyClear.md)  |  是  |  是  |  是  |  是  |  是  | 

### 注释运算符
<a name="mongo-apis-query-comment-operator"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1comment](comment.md)  |  支持  |  是  |  是  |  是  |  是  | 

### 比较运算符
<a name="mongo-apis-query-comparison-operators"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1eq](eq.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1gt](gt.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1gte](gte.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1in](in.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1lt](lt.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1lte](lte.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1ne](ne.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1nin](nin.md)  |  是  |  是  |  是  |  是  |  是  | 

### 元素运算符
<a name="mongo-apis-query-element-operators"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1exists](exists.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1type](type.md)  |  是  |  是  |  是  |  是  |  是  | 

### 评估查询运算符
<a name="mongo-apis-query-evaluation-operators"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1expr](expr.md)  |  否  |  是  |  是  |  是  |  否  | 
|  [\$1jsonSchema](jsonSchema.md)  |  否  |  是  |  是  |  是  |  否  | 
|  [\$1mod](mod-query.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1regex](regex.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1text](text.md)  |  否  |  否  |  是  |  是  |  否  | 
|  \$1where  |  否  |  否  |  否  |  否  |  否  | 

### 逻辑运算符
<a name="mongo-apis-query-logical-operators"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1and](and.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1nor](nor.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1not](not.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1or](or.md)  |  是  |  是  |  是  |  是  |  是  | 

### 投影运算符
<a name="mongo-apis-projection-operators"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1](dollar-projection.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1elemMatch](elemMatch.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1meta](meta.md)  |  否  |  否  |  是  |  是  |  否  | 
|  [\$1slice](slice-projection.md)  |  是  |  是  |  是  |  是  |  是  | 

## 更新运算符
<a name="mongo-apis-update"></a>

**Topics**
+ [数组运算符](#mongo-apis-update-array)
+ [按位运算符](#mongo-apis-update-bitwise)
+ [字段运算符](#mongo-apis-update-field)
+ [更新修改器](#mongo-apis-update-modifiers)

### 数组运算符
<a name="mongo-apis-update-array"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1](dollar-update.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1[]](dollarBrackets-update.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1[<identifier>]](dollarIdentifier-update.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1addToSet](addToSet.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1pop](pop.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1pullAll](pullAll.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1pull](pull.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1push](push.md)  |  支持  |  是  |  是  |  是  |  是  | 

### 按位运算符
<a name="mongo-apis-update-bitwise"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1bit](bit.md)  |  支持  |  是  |  是  |  是  |  是  | 

### 字段运算符
<a name="mongo-apis-update-field"></a>


| 运算符 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1currentDate](currentDate.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1inc](inc.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1max](max-update.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1min](min-update.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1mul](mul.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1rename](rename.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1set](set-update.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1setOnInsert](setOnInsert.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1unset](unset-update.md)  |  是  |  是  |  是  |  是  |  是  | 

### 更新修改器
<a name="mongo-apis-update-modifiers"></a>


| 运算符 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1each](each.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1position](position.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1slice](slice-update.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1sort](sort-update.md)  |  是  |  是  |  是  |  是  |  是  | 

## 地理空间
<a name="mongo-apis-geospatial"></a>

### 几何说明符
<a name="mongo-apis-geospatial-geometry-specifiers"></a>


| 查询选择器 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  BOX  |  否  |  否  |  否  |  否  |  否  | 
|  .center  |  否  |  否  |  否  |  否  |  否  | 
|  \$1centerSphere  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1geometry](geometry.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1maxDistance](maxDistance.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1minDistance](minDistance.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1nearSphere](nearSphere.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1polygon  |  否  |  否  |  否  |  否  |  否  | 
|  \$1uniqueDocs  |  否  |  否  |  否  |  否  |  否  | 

### 查询选择器
<a name="mongo-apis-geospatial-query-selectors"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1geoIntersects](geoIntersects.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1geoWithin](geoWithin.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1near](near.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1nearSphere](nearSphere.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1polygon  |  否  |  否  |  否  |  否  |  否  | 
|  \$1uniqueDocs  |  否  |  否  |  否  |  否  |  否  | 

## 游标方法
<a name="mongo-apis-cursor"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  cursor.batchSize()  |  支持  |  是  |  是  |  是  |  是  | 
|  cursor.close()  |  支持  |  是  |  是  |  是  |  是  | 
|  cursor.collation()  |  否  |  否  |  否  |  是  |  否  | 
|  cursor.comment()  |  支持  |  是  |  是  |  是  |  是  | 
|  cursor.count()  |  支持  |  是  |  是  |  是  |  是  | 
|  cursor.explain()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.forEach()  |  支持  |  是  |  是  |  是  |  是  | 
|  cursor.hasNext()  |  支持  |  是  |  是  |  是  |  是  | 
|  cursor.hint()  |  支持  |  是  |  是  |  是  |  是\$1  | 
|  cursor.isClosed()  |  支持  |  是  |  是  |  是  |  是  | 
|  cursor.isExhausted()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.itcount()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.limit()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.map()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.max()  |  否  |  否  |  否  |  否  |  否  | 
|  cursor.maxScan()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.maxTimeMS()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.min()  |  否  |  否  |  否  |  否  |  否  | 
|  cursor.next()  |  支持  |  是  |  是  |  是  |  是  | 
|  光标。 noCursorTimeout()  |  否  |  否  |  否  |  否  |  否  | 
|  光标。 objsLeftInBatch ()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.pretty()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.readConcern()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.readPref()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.returnKey()  |  否  |  否  |  否  |  否  |  否  | 
|  光标。 showRecordId()  |  否  |  否  |  否  |  否  |  否  | 
|  cursor.size()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.skip()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.sort()  |  支持  |  是  |  是  |  是  |  否  | 
|  cursor.tailable()  |  否  |  否  |  否  |  否  |  否  | 
|  cursor.toArray()  |  支持  |  是  |  是  |  是  |  否  | 

\$1 索引 `hint` 表达式支持索引。例如 `db.foo.find().hint({x:1})`。

## 聚合管道运算符
<a name="mongo-apis-aggregation-pipeline"></a>

**Topics**
+ [累加器表达式](#mongo-apis-aggregation-pipeline-accumulator-expressions)
+ [算术运算符](#mongo-apis-aggregation-pipeline-arithmetic)
+ [数组运算符](#mongo-apis-aggregation-pipeline-array)
+ [布尔运算符](#mongo-apis-aggregation-pipeline-boolean)
+ [比较运算符](#mongo-apis-aggregation-pipeline-comparison)
+ [条件表达式运算符](#mongo-apis-aggregation-pipeline-conditional)
+ [数据类型运算符](#mongo-apis-aggregation-pipeline-data-type)
+ [数据大小运算符](#mongo-apis-aggregation-pipeline-data-size)
+ [日期运算符](#mongo-apis-aggregation-pipeline-date)
+ [文字运算符](#mongo-apis-aggregation-pipeline-literal)
+ [合并运算符](#mongo-apis-aggregation-pipeline-merge)
+ [自然运算符](#mongo-apis-aggregation-pipeline-natural)
+ [集合运算符](#mongo-apis-aggregation-pipeline-set)
+ [阶段运算符](#mongo-apis-aggregation-pipeline-stage)
+ [字符串运算符](#mongo-apis-aggregation-pipeline-string)
+ [系统变量](#mongo-apis-aggregation-pipeline-system-variables)
+ [文本搜索运算符](#mongo-apis-aggregation-pipeline-text-search)
+ [类型转换运算符](#mongo-apis-aggregation-pipeline-type)
+ [变量运算符](#mongo-apis-aggregation-pipeline-variable)
+ [其他运算符](#mongo-apis-aggregation-pipeline-misc)

### 累加器表达式
<a name="mongo-apis-aggregation-pipeline-accumulator-expressions"></a>


| Expression | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1accumulator  |  -  |  -  |  否  |  否  |  否  | 
|  [\$1addToSet](addToSet-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1avg](avg.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1count](count.md)  |  -  |  -  |  否  |  否  |  否  | 
|  \$1covariancePop  |  否  |  否  |  否  |  否  |  否  | 
|  \$1covarianceSamp  |  否  |  否  |  否  |  否  |  否  | 
|  \$1denseRank  |  否  |  否  |  否  |  否  |  否  | 
|  \$1derivative  |  否  |  否  |  否  |  否  |  否  | 
|  \$1documentNumber  |  否  |  否  |  否  |  否  |  否  | 
|  \$1expMovingAvg  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1first](first.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1integral  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1last](last.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1max](max.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1min](min.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1push](push-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1rank  |  否  |  否  |  否  |  否  |  否  | 
|  \$1shift  |  否  |  否  |  否  |  否  |  否  | 
|  \$1stdDevPop  |  否  |  否  |  否  |  否  |  否  | 
|  \$1stdDevSamp  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1sum](sum.md)  |  是  |  是  |  是  |  是  |  是  | 

### 算术运算符
<a name="mongo-apis-aggregation-pipeline-arithmetic"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1abs](abs.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1add](add.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1ceil](ceil.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1divide](divide.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1exp](exp.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1floor](floor.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1ln](ln.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1log](log.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1log10](log10.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1mod](mod.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1multiply](multiply.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1pow](pow.md)  |  否  |  否  |  否  |  是  |  否  | 
|  \$1round  |  -  |  -  |  否  |  否  |  否  | 
|  [\$1sqrt](sqrt.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1subtract](subtract.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1trunc  |  否  |  否  |  否  |  否  |  否  | 

### 数组运算符
<a name="mongo-apis-aggregation-pipeline-array"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1arrayElemAt](arrayElemAt.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1arrayToObject](arrayToObject.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1concatArrays](concatArrays.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1filter](filter.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1first](first.md)  |  -  |  -  |  是  |  是  |  否  | 
|  [\$1in](in-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1indexOfArray](indexOfArray.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1isArray](isArray.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1last](last.md)  |  -  |  -  |  是  |  是  |  否  | 
|  [\$1objectToArray](objectToArray.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1range](range.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1reverseArray](reverseArray.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1reduce](reduce.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1size](size.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1slice](slice.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1zip](zip.md)  |  是  |  是  |  是  |  是  |  是  | 

### 布尔运算符
<a name="mongo-apis-aggregation-pipeline-boolean"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1and](and-aggregation.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1not](not-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1or](or-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 

### 比较运算符
<a name="mongo-apis-aggregation-pipeline-comparison"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1cmp](cmp.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1eq](eq-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1gt](gt-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1gte](gte-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1lt](lt-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1lte](lte-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1ne](ne-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 

### 条件表达式运算符
<a name="mongo-apis-aggregation-pipeline-conditional"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1cond](cond.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1ifNull](ifNull.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1switch](switch.md)  |  否  |  是  |  是  |  是  |  否  | 

### 数据类型运算符
<a name="mongo-apis-aggregation-pipeline-data-type"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1type](type-aggregation.md)  |  支持  |  是  |  是  |  是  |  是  | 

### 数据大小运算符
<a name="mongo-apis-aggregation-pipeline-data-size"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1binarySize  |  -  |  -  |  否  |  否  |  否  | 
|  \$1bsonSize  |  -  |  -  |  否  |  否  |  否  | 

### 日期运算符
<a name="mongo-apis-aggregation-pipeline-date"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1dateAdd](dateAdd.md)  |  否  |  否  |  是  |  是  |  是  | 
|  [\$1dateDiff](dateDiff.md)  |  -  |  -  |  是  |  是  |  否  | 
|  \$1dateFromParts  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1dateFromString](dateFromString.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1dateSubtract](dateSubtract.md)  |  否  |  否  |  是  |  是  |  是  | 
|  \$1dateToParts  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1dateToString](dateToString.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1dateTrunc](dateTrunc.md)  |  -  |  -  |  否  |  是  |  否  | 
|  [\$1dayOfMonth](dayOfMonth.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1dayOfWeek](dayOfWeek.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1dayOfYear](dayOfYear.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1hour](hour.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1 isoDayOf 周](isoDayOfWeek.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1isoWeek](isoWeek.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1isoWeekYear](isoWeekYear.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1millisecond](millisecond.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1minute](minute.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1month](month.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1second](second.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1week](week.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1year](year.md)  |  是  |  是  |  是  |  是  |  是  | 

### 文字运算符
<a name="mongo-apis-aggregation-pipeline-literal"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1literal](literal.md)  |  支持  |  是  |  是  |  是  |  是  | 

### 合并运算符
<a name="mongo-apis-aggregation-pipeline-merge"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1mergeObjects](mergeObjects.md)  |  支持  |  是  |  是  |  是  |  是  | 

### 自然运算符
<a name="mongo-apis-aggregation-pipeline-natural"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1natural](natural.md)  |  支持  |  是  |  是  |  是  |  是  | 

### 集合运算符
<a name="mongo-apis-aggregation-pipeline-set"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1allElementsTrue](allElementsTrue.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1anyElementTrue](anyElementTrue.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1setDifference](setDifference.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1setEquals](setEquals.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1setIntersection](setIntersection.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1setIsSubset](setIsSubset.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1setUnion](setUnion.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1setWindowFields  |  否  |  否  |  否  |  否  |  否  | 

### 阶段运算符
<a name="mongo-apis-aggregation-pipeline-stage"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1addFields](addFields.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1bucket](bucket.md)  |  否  |  否  |  否  |  是  |  否  | 
|  \$1bucketAuto  |  否  |  否  |  否  |  否  | 
|  [\$1changeStream](changeStream.md)  |  是  |  是  |  是  |  是  |  否  | 
|  [\$1collStats](collStats.md)  |  否  |  是  |  是  |  是  |  否  | 
|  [\$1count](count.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1currentOp](currentOp.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1facet  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1geoNear](geoNear.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1graphLookup  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1group](group.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1indexStats](indexStats.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1limit](limit.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1listLocalSessions  |  否  |  否  |  否  |  否  |  否  | 
|  \$1listSessions  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1lookup](lookup.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1match](match.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [merge](merge.md)  |  -  |  -  |  否  |  是  |  否  | 
|  [\$1out](out.md)  |  是  |  是  |  是  |  是  |  否  | 
|  \$1planCacheStats  |  -  |  -  |  否  |  否  |  否  | 
|  [\$1project](project.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1redact](redact.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1replaceRoot](replaceRoot.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1sample](sample.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1set](set-stage.md)  |  -  |  -  |  否  |  是  |  否  | 
|  \$1setWindowFields  |  -  |  -  |  否  |  否  |  否  | 
|  [\$1skip](skip.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1sort](sort.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1sortByCount  |  否  |  否  |  否  |  否  |  否  | 
|  \$1unionWith  |  -  |  -  |  否  |  否  |  否  | 
|  [\$1unset](unset-stage.md)  |  -  |  -  |  否  |  是  |  否  | 
|  [\$1unwind](unwind.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1replaceWith](replaceWith.md)  |  否  |  否  |  否  |  是  |  否  | 
|  [\$1向量搜索](vectorSearch.md)  |  否  |  否  |  否  |  是  |  否  | 

### 字符串运算符
<a name="mongo-apis-aggregation-pipeline-string"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1concat](concat.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1indexOfBytes](indexOfBytes.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1indexOfCP](indexOfCP.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1ltrim](ltrim.md)  |  否  |  是  |  是  |  是  |  否  | 
|  [\$1regexFind](regexFind.md)  |  -  |  -  |  是  |  是  |  否  | 
|  [\$1regexFindAll](regexFindAll.md)  |  -  |  -  |  是  |  是  |  否  | 
|  [\$1regexMatch](regexMatch.md)  |  -  |  -  |  是  |  是  |  否  | 
|  [\$1replaceAll](replaceAll.md)  |  -  |  -  |  是  |  是  |  否  | 
|  [\$1replaceOne](replaceOne.md)  |  -  |  -  |  是  |  是  |  否  | 
|  [\$1rtrim](rtrim.md)  |  否  |  是  |  是  |  是  |  否  | 
|  [\$1split](split.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1strcasecmp](strcasecmp.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1strLenBytes](strLenBytes.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1strLenCP](strLenCP.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1substr](substr.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1substrBytes](substrBytes.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1substrCP](substrCP.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1toLower](toLower.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1toUpper](toUpper.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1trim](trim.md)  |  否  |  是  |  是  |  是  |  否  | 

### 系统变量
<a name="mongo-apis-aggregation-pipeline-system-variables"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1\$1CURRENT  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1\$1DESCEND](DESCEND.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1\$1KEEP](KEEP.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1\$1PRUNE](PRUNE.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1\$1REMOVE  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1ROOT](ROOT.md)  |  是  |  是  |  是  |  是  |  是  | 

### 文本搜索运算符
<a name="mongo-apis-aggregation-pipeline-text-search"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1meta](meta-aggregation.md)  |  否  |  否  |  是  |  是  |  否  | 
|  [\$1search](search.md)  |  否  |  否  |  是  |  是  |  否  | 

### 类型转换运算符
<a name="mongo-apis-aggregation-pipeline-type"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1convert](convert.md)  |  否  |  是  |  是  |  是  |  是  | 
|  \$1isNumber  |  -  |  -  |  否  |  否  |  否  | 
|  [\$1toBool](toBool.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1toDate](toDate.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1toDecimal](toDecimal.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1toDouble](toDouble.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1toInt](toInt.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1toLong](toLong.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1toObjectId](toObjectId.md)  |  否  |  是  |  是  |  是  |  是  | 
|  [\$1toString](toString.md)  |  否  |  是  |  是  |  是  |  是  | 

### 变量运算符
<a name="mongo-apis-aggregation-pipeline-variable"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1let](let.md)  |  支持  |  是  |  是  |  是  |  是  | 
|  [\$1map](map.md)  |  是  |  是  |  是  |  是  |  是  | 

### 其他运算符
<a name="mongo-apis-aggregation-pipeline-misc"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1getField  |  -  |  -  |  否  |  否  |  否  | 
|  [\$1rand](rand.md)  |  -  |  -  |  否  |  是  |  否  | 
|  \$1sampleRate  |  -  |  -  |  否  |  否  |  否  | 

## 数据类型
<a name="mongo-apis-data-types"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  32-bit Integer (int)  |  支持  |  是  |  是  |  是  |  是  | 
|  64-bit Integer (long)  |  支持  |  是  |  是  |  是  |  是  | 
|  数组  |  支持  |  是  |  是  |  是  |  是  | 
|  二进制数据  |  支持  |  是  |  是  |  是  |  是  | 
|  布尔值  |  支持  |  是  |  是  |  是  |  是  | 
|  日期  |  支持  |  是  |  是  |  是  |  是  | 
|  DBPointer  |  否  |  否  |  否  |  否  |  否  | 
|  DBRefs  |  否  |  否  |  否  |  否  |  否  | 
|  Decimal128  |  支持  |  是  |  是  |  是  |  是  | 
|  双精度  |  支持  |  是  |  是  |  是  |  是  | 
|  JavaScript  |  否  |  否  |  否  |  否  |  否  | 
|  JavaScript（带瞄准镜）  |  否  |  否  |  否  |  否  |  否  | 
|  MaxKey  |  是  |  是  |  是  |  是  |  是  | 
|  MinKey  |  是  |  是  |  是  |  是  |  是  | 
|  Null  |  支持  |  是  |  是  |  是  |  是  | 
|  对象  |  支持  |  是  |  是  |  是  |  是  | 
|  ObjectId  |  是  |  是  |  是  |  是  |  是  | 
|  正则表达式  |  支持  |  是  |  是  |  是  |  是  | 
|  字符串  |  是  |  是  |  是  |  是  |  是  | 
|  符号  |  否  |  否  |  否  |  否  |  否  | 
|  Timestamp  |  支持  |  是  |  是  |  是  |  是  | 
|  未定义  |  否  |  否  |  否  |  否  |  否  | 

## 索引和索引属性
<a name="mongo-apis-index"></a>

**Topics**
+ [索引](#mongo-apis-indexes)
+ [索引属性](#mongo-apis-index-properties)

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


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  2dsphere  |  支持  |  是  |  是  |  是  |  是  | 
|  2d 索引  |  否  |  否  |  否  |  否  |  否  | 
|  复合索引  |  支持  |  是  |  是  |  是  |  是  | 
|  哈希索引  |  否  |  否  |  否  |  否  |  否  | 
|  多键索引  |  支持  |  是  |  是  |  是  |  是  | 
|  单个字段索引  |  支持  |  是  |  是  |  是  |  是  | 
|  文本索引  |  否  |  否  |  是  |  是  |  否  | 
|  通配符  |  否  |  否  |  否  |  否  |  否  | 

### 索引属性
<a name="mongo-apis-index-properties"></a>


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
|  背景  |  支持  |  是  |  是  |  是  |  是  | 
|  区分大小写  |  否  |  否  |  否  |  是  |  否  | 
|  隐藏  |  否  |  否  |  否  |  否  |  否  | 
|  部分  |  否  |  否  |  是  |  是  |  否  | 
|  稀疏  |  支持  |  是  |  是  |  是  |  是  | 
|  文本  |  否  |  否  |  是  |  是  |  否  | 
|  TTL  |  支持  |  是  |  是  |  是  |  是  | 
|  Unique  |  支持  |  是  |  是  |  是  |  是  | 
|  向量  |  否  |  否  |  是  |  是  |  否  | 

有关特定 MongoDB 运算符的详细信息，请参阅以下主题：
+ [聚合管道运算符](mongo-apis-aggregation-pipeline-operators.md)
+ [地理空间](mongo-apis-geospatial-operators.md)
+ [投影运算符](#mongo-apis-projection-operators)
+ [更新运算符](mongo-apis-update-operators.md)

# 聚合管道运算符
<a name="mongo-apis-aggregation-pipeline-operators"></a>

本节提供有关 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)
+ [\$1 isoDayOf 周](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)
+ [merge](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)
+ [\$1向量搜索](vectorSearch.md)
+ [\$1week](week.md)
+ [\$1year](year.md)
+ [\$1zip](zip.md)

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

Amazon DocumentDB 中的`$$DESCEND`运算符是管道阶段中使用的特殊位置数组运算符。`$redact`它指示聚合管道进入当前文档并处理所有字段，无论其嵌套级别如何。

当`$redact`舞台遇到`$$DESCEND`操作员时，它将保持当前文档中的所有字段可见，并在管道中进一步处理它们。当你想根据条件有选择地编辑或修剪某些字段，同时保留文档的结构时，这很有用。

**参数**

无。

## 示例（MongoDB 外壳）
<a name="DESCEND-examples"></a>

在此示例中，我们将使用带有`$$DESCEND`运算符的`$redact`舞台来有选择地显示`code`字段等于 “Reg” 的文档。

**创建示例文档**

```
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" }
]);
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="DESCEND-code"></a>

要查看使用该`$$DESCEND`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$$KEEP`系统变量与聚合管道中的`$redact`阶段一起使用，以保持当前文档或字段不变，并将其包含在输出中。

**参数**

无

## 示例（MongoDB 外壳）
<a name="KEEP-examples"></a>

以下示例演示了在 Amazon DocumentDB 聚合管道`$$KEEP`中的用法。只有当访问权限等于 “公开” 时，才会保留文档，否则它们将被删除。

**创建示例文档**

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

**查询示例**

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

**输出**

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

## 代码示例
<a name="KEEP-code"></a>

要查看使用该`$$KEEP`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$$PRUNE`系统变量与聚合管道中的`$redact`阶段一起使用，从结果中排除文档或嵌入式文档级别。当条件计算为时`$$PRUNE`，当前文档或子文档将从输出中删除。它通常与`$$DESCEND`（用于保留和遍历文档）或`$$KEEP`（将文档保持在所有级别）一起使用。

**参数**

无。`$$PRUNE`系统变量不带任何参数，必须与一起使用`$redact`。

## 示例（MongoDB 外壳）
<a name="PRUNE-examples"></a>

以下示例演示如何`$$PRUNE`使用和将 30 岁`$redact`以上的用户排除在结果之外。

**创建示例文档**

```
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" } }
])
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="PRUNE-code"></a>

要查看使用该`$$PRUNE`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$ROOT`运算符用于引用聚合管道中的整个输入文档。它允许您访问和操作完整的文档，包括其所有嵌套字段和结构。

**参数**

无

## 示例（MongoDB 外壳）
<a name="ROOT-examples"></a>

此示例演示`$ROOT`如何使用创建审核日志，该日志可捕获完整的原始文档以及有关文档处理时间的元数据。

**创建示例文档**

```
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
  }
]);
```

**查询示例**

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

**输出**

```
[
  {
    _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'
  }
]
```

## 代码示例
<a name="ROOT-code"></a>

要查看使用该`$ROOT`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$abs`运算符返回数字的绝对值。它可以在聚合管道中用于对数值字段执行数学运算。

**参数**
+ `number`：将返回其绝对值的数值表达式。

## 示例（MongoDB 外壳）
<a name="abs-examples"></a>

此示例演示如何使用`$abs`运算符来查找数值字段的绝对值。

**创建示例文档**

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

**查询示例**

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

**输出**

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

## 代码示例
<a name="abs-code"></a>

要查看使用该`$abs`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$add`运算符用于将数字或日期相加。它可用于对数值字段执行算术运算，或者通过向日期字段添加多个时间单位来执行日期算术。

**参数**
+ `expression1`：要添加的第一个数字或日期。
+ `expression2`：要添加的第二个数字或日期。
+ `expression3`:（可选）要添加的其他数字或日期。

## 示例（MongoDB 外壳）
<a name="add-examples"></a>

以下示例演示如何使用`$add`运算符将两个数字相加。

**创建示例文档**

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

**查询示例**

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

**输出**

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

在此示例中，`$add`运算符用于为每个文档添加`a`和`b`字段的值，并将结果存储在`sum`字段中。

## 代码示例
<a name="add-code"></a>

要查看使用该`$add`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$addToSet`聚合运算符从每个组的指定表达式中返回一个由唯一值组成的数组。它在`$group`舞台中用于累积不同的值，从而自动消除重复值。

**参数**
+ `expression`：要为组中的每个文档计算的表达式。

## 示例（MongoDB 外壳）
<a name="addToSet-aggregation-examples"></a>

以下示例演示如何使用`$addToSet`运算符收集为每个客户下单的独特城市。

**创建示例文档**

```
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 }
]);
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="addToSet-aggregation-code"></a>

要查看使用`$addToSet`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 聚合管道中的`$addFields`阶段允许您向文档添加新的计算字段。这对于向文档中添加派生或转换后的数据非常有用。

**参数**
+ `newField`：要添加的新字段的名称。
+ `expression`：解析为新字段值的表达式。

## 示例（MongoDB 外壳）
<a name="addFields-examples"></a>

以下示例演示`$addFields`如何使用添加新字段`TotalInventory`，该字段根据`Inventory.OnHand`和`Inventory.OrderQnty`字段计算总库存。

**创建示例文档**

```
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
  }
]);
```

**查询示例**

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

**输出**

```
[
  {
    "_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
  }
]
```

## 代码示例
<a name="addFields-code"></a>

要查看使用该`$addFields`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

该`$allElementsTrue`运算符用于检查数组中所有元素的计算结果是否为真值。

**参数**
+ `expression`: 计算结果为数组的表达式。

## 示例（MongoDB 外壳）
<a name="allElementsTrue-examples"></a>

以下示例演示了检查数组中所有元素是否为真时的用法。`$allElementsTrue`

**创建示例文档**

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

**查询示例**

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

**输出**

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

在此示例中，查询检查`scores`数组中的所有元素是否都大于 0。之所以排除带的`&quot;name&quot;: &quot;Jane&quot;`文档，是因为该`scores`数组包含一个 0，这是一个虚假值。

## 代码示例
<a name="allElementsTrue-code"></a>

要查看使用该`$allElementsTrue`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$and`聚合运算符计算多个表达式，并且`true`仅当所有表达式的计算结果均为`true`时才返回。如果有任何表达式`false`，则返回`false`。

**参数**
+ `expressions`：要计算的表达式数组。

## 示例（MongoDB 外壳）
<a name="and-aggregation-examples"></a>

以下示例演示如何使用`$and`运算符来检查产品是否满足多个标准。

**创建示例文档**

```
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 }
]);
```

**查询示例**

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

**输出**

```
[
  { _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 }
]
```

## 代码示例
<a name="and-aggregation-code"></a>

要查看使用`$and`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

该`$anyElementTrue`运算符用于确定数组中是否有任何元素为真。

**参数**
+ `field`: 要评估的数组字段。

## 示例（MongoDB 外壳）
<a name="anyElementTrue-examples"></a>

以下示例演示了检查数`$anyElementTrue`组中是否有任何元素为真值的用法。

**创建示例文档**

```
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] }
])
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="anyElementTrue-code"></a>

要查看使用该`$anyElementTrue`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$arrayElemAt`运算符允许您按索引位置从数组中检索元素。当您需要访问文档中数组字段中的特定元素时，这特别有用。

**参数**
+ `array`: 要从中检索元素的输入数组。
+ `index`：要检索的元素从零开始的索引位置。此值必须是非负整数。

## 示例（MongoDB 外壳）
<a name="arrayElemAt-examples"></a>

在此示例中，我们将演示如何使用`$arrayElemAt`运算符从`miles`集合中的`flight_miles`数组中检索特定元素。

**创建示例文档**

```
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 ]}
]);
```

**查询示例**

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

**输出**

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

在此示例中，我们使用`$arrayElemAt`运算符为每个文档检索`flight_miles`数组的第一个和最后一个元素。

## 代码示例
<a name="arrayElemAt-code"></a>

要查看使用该`$arrayElemAt`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$arrayToObject`运算符与运算符相反。`$objectToArray`它接受一组键值对文档并将其转换为单个文档。当你需要将一组键值对转换回对象或文档结构时，这特别有用。

**参数**
+ `array expression`: 解析为数组的表达式。数组元素必须是包含两个字段的文档：`k`（键）和`v`（值）。

## 示例（MongoDB 外壳）
<a name="arrayToObject-examples"></a>

下面的示例演示了`$arrayToObject`如何使用将键值对数组转换回文档。

**创建示例文档**

```
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 } }
]);
```

**查询示例**

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

**输出**

```
{ "_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 } }
```

在此示例中，`$objectToArray`运算符用于将`inventory`对象转换为键值对数组。然后使用该`$arrayToObject`运算符将数组转换回文档，从而恢复原始对象结构。

## 代码示例
<a name="arrayToObject-code"></a>

要查看使用该`$arrayToObject`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$avg`聚合运算符计算输入到舞台的文档中指定表达式的平均值。此运算符可用于计算一组文档中数值字段或表达式的平均值。

**参数**
+ `expression`：用于计算平均值的表达式。这可以是字段路径（例如`"$field"`）或表达式（例如`{ $multiply: ["$field1", "$field2"] }`）。

## 示例（MongoDB 外壳）
<a name="avg-examples"></a>

以下示例演示如何使用`$avg`运算符计算一组学生文档的平均分数。

**创建示例文档**

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

**查询示例**

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

**输出**

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

## 代码示例
<a name="avg-code"></a>

要查看使用该`$avg`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

8.0 版的新增内容

弹性集群不支持。

Amazon DocumentDB 中的`$bucket`聚合阶段允许您根据指定的表达式和存储桶边界将输入文档分组到存储桶中。这对于分析属于特定值范围或类别的数据非常有用。

**参数**
+ `groupBy`（必填）：指定分组依据的值的表达式。
+ `boundaries`（必填）：定义存储桶边界的双精度值数组。根据位于指定边界内的`groupBy`表达式值将文档分配给存储桶。
+ `default`（可选）：为`groupBy`表达式值不属于任何指定边界的文档输出的文字值。
+ `output`（可选）：一个对象，它指定要为每个存储桶输出的信息。您可以使用诸如`$sum`、`$avg``$min`、和之类的累加器运算符`$max`来计算每个存储桶的聚合。

## 示例（MongoDB 外壳）
<a name="bucket-examples"></a>

以下示例演示如何使用`$bucket`舞台按价格区间对销售数据进行分组。

**创建示例文档**

```
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") }
]);
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="bucket-code"></a>

要查看使用该`$bucket`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

与 MongoDB 一样，Amazon DocumentDB 中的`$ceil`运算符将数字向上舍入到最接近的整数。当您需要对数值字段执行数学运算并确保结果为整数时，这很有用。

**参数**
+ `expression`: 要向上舍入的数值表达式。

## 示例（MongoDB 外壳）
<a name="ceil-examples"></a>

此示例演示如何使用`$ceil`运算符向上舍入数值字段。

**创建示例文档**

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

**查询示例**

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

**输出**

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

## 代码示例
<a name="ceil-code"></a>

要查看使用该`$ceil`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

弹性集群不支持。

`$changeStream`聚合阶段会打开更改流游标，以监视集合的实时更改。当进行插入、更新、替换或删除操作时，它会返回更改事件文档。

**参数**
+ `fullDocument`：指定是否返回完整文档以进行更新操作。选项有 `default` 或 `updateLookup`。
+ `resumeAfter`: 可选。恢复令牌以从变更流中的特定点继续。
+ `startAtOperationTime`: 可选。开始变更流的时间戳。
+ `allChangesForCluster`: 可选。布尔值。何时`true`，监视集群中的所有更改（对于管理员数据库）。当`false`（默认）时，仅监视指定的集合。

## 示例（MongoDB 外壳）
<a name="changeStream-examples"></a>

以下示例演示了如何使用`$changeStream`舞台来监视集合的更改。

**查询示例**

```
// 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()));
}
```

**输出**

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

## 代码示例
<a name="changeStream-code"></a>

要查看使用`$changeStream`聚合阶段的代码示例，请选择要使用的语言对应的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$cmp`运算符用于比较两个值并返回一个表示其相对顺序的整数值。它是一个比较运算符，它比较两个表达式并分别返回 -1、0 或 1 的整数值，具体取决于第一个值是小于、等于还是大于第二个值。

**参数**
+ `expression1`：第一个要比较的表达式。
+ `expression2`：第二个要比较的表达式。

## 示例（MongoDB 外壳）
<a name="cmp-examples"></a>

以下示例演示如何使用运`$cmp`算符比较两个数值。

**创建示例文档**

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

**查询示例**

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

**输出**

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

在此示例中，`$cmp`运算符比较每个文档的`value1`和`value2`字段。结果是：

```
- `$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).
```

## 代码示例
<a name="cmp-code"></a>

要查看使用该`$cmp`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是在带有`mongodb`驱动程序的 Node.js 应用程序中使用`$cmp`运算符的示例：

```
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 ]

以下是在带`pymongo`驱动程序的 Python 应用程序中使用`$cmp`运算符的示例：

```
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()
```

Node.js 和 Python 示例的输出都将与 MongoDB Shell 示例的输出相同：

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

------

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

4.0 版的新增内容

Amazon DocumentDB 中的`$collStats`聚合阶段提供有关指定集合的统计信息，类似于 MongoDB 外壳中的`db.collection.stats()`命令。此阶段可用于检索有关集合的信息，例如文档数量、集合的总大小以及各种性能指标。

**参数**
+ `latencyStats`:（可选）指定收集延迟统计信息的选项的文档。Amazon DocumentDB 不支持此参数。
+ `recordStats`:（可选）指定收集记录统计信息的选项的文档。Amazon DocumentDB 不支持此参数。
+ `queryExecStats`:（可选）一个文档，它指定了用于收集查询执行统计信息的选项。Amazon DocumentDB 不支持此参数。

## 示例（MongoDB 外壳）
<a name="collStats-examples"></a>

以下示例演示如何使用`$collStats`聚合阶段检索有关`db`数据库`test`中名为的集合的统计信息。

**创建示例文档**

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

**查询示例**

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

**输出**

```
{
  "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)
}
```

## 代码示例
<a name="collStats-code"></a>

要查看使用该`$collStats`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是如何使用官方 MongoDB Node.js 驱动程序在 Node.js 应用程序中使用`$collStats`聚合阶段的示例：

```
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 ]

以下是如何使用 PyMongo 驱动程序在 Python 应用程序中使用`$collStats`聚合阶段的示例：

```
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>

Amazon DocumentDB 中的`$concat`聚合运算符连接（或组合）文档中的多个字符串，生成一个可以返回给应用程序的字符串。这减少了在应用程序中完成的工作，因为字符串操作是在数据库级别执行的。

**参数**
+ `expression1`: 要连接的第一个字符串。
+ `expression2`: 要连接的第二个字符串。
+ `...`：要连接的其他字符串（可选）。

## 示例（MongoDB 外壳）
<a name="concat-examples"></a>

在此示例中，我们将用户的名字和姓氏连接起来生成每个人的全名。

**创建示例文档**

```
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"}
])
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="concat-code"></a>

要查看使用该`$concat`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$concatArrays`聚合运算符用于将两个或多个数组连接成一个数组。当您需要将多个数据数组组合成一个数组以进行进一步处理或分析时，这可能很有用。

**参数**
+ `array1`: 第一个要连接的数组。
+ `array2`: 要连接的第二个数组。
+ `[array3, ...]`:（可选）要连接的其他数组。

## 示例（MongoDB 外壳）
<a name="concatArrays-examples"></a>

以下示例演示如何使用`$concatArrays`运算符将两个数组合并为一个数组。

**创建示例文档**

```
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"]
  }
]);
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="concatArrays-code"></a>

要查看使用该`$concatArrays`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$cond`运算符用于计算条件表达式并返回两个可能的结果表达式之一。

**参数**
+ `if`: 要计算的布尔表达式。
+ `then`：如果表达式为真则返回的`if`表达式。
+ `else`：如果表达式为假则返回的`if`表达式。

## 示例（MongoDB 外壳）
<a name="cond-examples"></a>

以下示例演示如何使用`$cond`运算符根据一个人的年龄返回值。

**创建示例文档**

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

**查询示例**

```
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"
            }
          }
        }
      }
    }
  }
])
```

**输出**

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

## 代码示例
<a name="cond-code"></a>

要查看使用该`$cond`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$convert`运算符用于将值从一种数据类型转换为另一种数据类型。当您需要对不同类型的数据执行操作时，此运算符很有用，例如将字符串转换为数字或将日期转换为时间戳。

**参数**
+ `to`：要将值转换为的目标数据类型。支持的值有 `"string"`、`"double"`、`"long"`、`"int"`、`"date"` 和 `"boolean"`。
+ `from`：该值的当前数据类型。如果未指定，Amazon DocumentDB 将尝试自动检测数据类型。
+ `onError`:（可选）转换失败时要返回的值。可以是特定值或以下特殊值之一：`"null"``"zerofill"`、或`"error"`。
+ `onNull`:（可选）如果输入值为，则返回的值`null`。可以是特定值或以下特殊值之一：`"null"``"zerofill"`、或`"error"`。

## 示例（MongoDB 外壳）
<a name="convert-examples"></a>

以下示例演示如何使用`$convert`运算符将字符串值转换为日期。

**创建示例文档**

```
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" }
]);
```

**查询示例**

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

**输出**

```
[
  { "_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 }
]
```

## 代码示例
<a name="convert-code"></a>

要查看使用该`$convert`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$count`聚合阶段用于计算进入该阶段的文档数量。它通常用作聚合管道的最后一个阶段，用于返回与前几个阶段匹配的文档总数。

**参数**
+ `field`：要计数的字段。此参数是可选的，如果未提供，则该阶段将计算输入文档的总数。

## 示例（MongoDB 外壳）
<a name="count-examples"></a>

以下示例演示如何使用`$count`舞台获取集合中的文档总数。

**创建示例文档**

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

**查询示例**

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

**输出**

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

该示例汇总了`users`集合，并使用`$count`舞台来计算文档的总数。

## 代码示例
<a name="count-code"></a>

要查看使用该`$count`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$currentOp`聚合阶段返回有关数据库中当前正在运行的操作的信息。此阶段对于监控聚合管道中的活动查询和操作非常有用。

**参数**
+ `allUsers`（可选）：如果设置为`true`，则返回所有用户的操作。默认值为 `false`。
+ `idleConnections`（可选）：设置为时`true`，包括空闲连接。默认值为 `false`。
+ `idleCursors`（可选）：如果设置为`true`，则包含有关空闲光标的信息。默认值为 `false`。
+ `idleSessions`（可选）：如果设置为`true`，则包含有关空闲会话的信息。默认值为 `true`。
+ `localOps`（可选）：设置为时`true`，包括本地操作。默认值为 `false`。

## 示例（MongoDB 外壳）
<a name="currentOp-examples"></a>

以下示例演示如何使用`$currentOp`聚合阶段检索有关活动读取操作的信息。

**查询示例**

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

**输出**

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

## 代码示例
<a name="currentOp-code"></a>

要查看使用该`$currentOp`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

5.0 版的新增内容

Amazon DocumentDB 中的`$dateAdd`聚合运算符允许您在日期和时间值中添加持续时间。

**参数**
+ `date`：用于添加持续时间的日期和时间值。
+ `duration`：要添加到该`date`值中的持续时间。可以将其指定为带有`years`、、、、`months``weeks``days``hours``minutes`、和键的对象`seconds`。
+ `timezone`:（可选）执行日期添加时要使用的时区。如果未指定，则使用 Amazon DocumentDB 集群的默认时区。

## 示例（MongoDB 外壳）
<a name="dateAdd-examples"></a>

以下示例演示如何使用`$dateAdd`运算符为日期添加 2 天零 12 小时。

**创建示例文档**

```
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") }
]);
```

**查询示例**

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

**输出**

```
[
  {
    "_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)"
  }
]
```

## 代码示例
<a name="dateAdd-code"></a>

要查看使用该`$dateAdd`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

5.0 版的新增内容

弹性集群不支持。

`$dateDiff`聚合运算符以指定单位计算两个日期之间的差。它返回开始日期和结束日期之间跨越单位边界的数量。

**参数**
+ `startDate`：开始日期表达式。
+ `endDate`：结束日期表达式。
+ `unit`: 差异的时间单位。支持的单位是`year`、`quarter`、`month`、`week`、`day`、`hour`、`minute`、`second`、和`millisecond`。

## 示例（MongoDB 外壳）
<a name="dateDiff-examples"></a>

以下示例演示如何使用`$dateDiff`运算符来计算从下单到交货之间的天数。

**创建示例文档**

```
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")
  }
]);
```

**查询示例**

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

**输出**

```
[
  {
    _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
  }
]
```

## 代码示例
<a name="dateDiff-code"></a>

要查看使用该`$dateDiff`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$dateFromString`聚合运算符允许您将日期时间字符串转换为日期对象。当您的数据存储为字符串但需要对数据执行基于日期的操作时，这很有用。

**参数**
+ `dateString`：表示日期和时间的字符串。
+ `format`:（可选）指定格式的字符串`dateString`。如果未提供，Amazon DocumentDB 将尝试以 ISO-8601 格式解析字符串。
+ `timezone`:（可选）指定时区的字符串。如果未提供，Amazon DocumentDB 将使用服务器的时区。
+ `onError`:（可选）指定转换失败时要采取的操作。可能的值是`'error'`（默认值，会引发错误）、`'null'`（返回`null`）或`'replace'`（用`onErrorMessage`选项中指定的替换字符串替换值）。
+ `onErrorMessage`:（可选）如果设置`onError`为`'replace'`，则此选项指定替换字符串。

## 示例（MongoDB 外壳）
<a name="dateFromString-examples"></a>

以下示例演示了`$dateFromString`如何使用在 Amazon DocumentDB 中将日期字符串转换为日期对象。

**创建示例文档**

```
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"}
]);
```

**查询示例**

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

**输出**

```
[
  {
    "_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")
  }
]
```

## 代码示例
<a name="dateFromString-code"></a>

要查看使用该`$dateFromString`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

5.0 版的新增内容

Amazon DocumentDB 中的`$dateSubtract`聚合运算符允许您从日期值中减去指定的持续时间。

**参数**
+ `date`：解析为日期或时间戳的日期表达式。
+ `subtrahend`：一个持续时间表达式，它指定要从表达`date`式中减去的时间长度。
+ `unit`：一个字符串，它指定`subtrahend`表达式的时间单位。支持的单位为 “年”、“季度”、“月”、“周”、“天”、“小时”、“分钟”、“秒” 和 “毫秒”。

## 示例（MongoDB 外壳）
<a name="dateSubtract-examples"></a>

以下示例演示如何使用`$dateSubtract`运算符从当前日期开始计算一年前的日期。

**创建示例文档**

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

**查询示例**

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

**输出**

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

## 代码示例
<a name="dateSubtract-code"></a>

要查看使用该`$dateSubtract`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$dateToString`聚合运算符用于将日期或时间戳值转换为字符串表示形式。当您需要以特定方式格式化日期和时间以进行显示或进一步处理时，这很有用。

**参数**
+ `date`：要转换为字符串的日期或时间戳值。
+ `format`：一个字符串，它指定应以何种格式表示日期。格式字符串可以包含各种格式说明符，例如`%Y`四位数年份、`%m`两位数月份、`%d`两位数月份的日期等。
+ `timezone`:（可选）用于转换的时区。如果未指定，则使用托管 Amazon DocumentDB 集群的服务器的时区。
+ `onNull`:（可选）如果`date`参数为，则返回的值`null`。

## 示例（MongoDB 外壳）
<a name="dateToString-examples"></a>

以下示例演示了如何使用运`$dateToString`算符来格式化`missionLog`集合的`logDate`字段。

**创建示例文档**

```
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") }
]);
```

**查询示例**

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

**输出**

```
[
  {
    "_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"
  }
]
```

## 代码示例
<a name="dateToString-code"></a>

要查看使用该`$dateToString`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是在 Node.js 应用程序中使用`$dateToString`运算符的示例：

```
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 ]

以下是在 Python 应用程序中使用`$dateToString`运算符的示例：

```
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>

8.0 版的新增内容

弹性集群不支持。

Amazon DocumentDB 中的`$dateTrunc`聚合运算符将日期截断为指定单位。

**参数**
+ `date`：解析为日期或时间戳的日期表达式。
+ `unit`：一个字符串，它为子集表达式指定时间单位。支持的单位是`year`、`quarter`、`month`、`week`、`day`、`hour`、`minute`、`second`、和`millisecond`。

## 示例（MongoDB 外壳）
<a name="dateTrunc-examples"></a>

以下示例演示如何使用`$dateTrunc`运算符将日期截断为小时。

**创建示例文档**

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

**查询示例**

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

**输出**

```
[
  {
    _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')
  }
]
```

## 代码示例
<a name="dateTrunc-code"></a>

要查看使用该`$dateTrunc`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$dayOfMonth`聚合运算符检索给定日期的当月中的某一天（从 1 到 31）。此运算符可用于对文档中的日期字段进行分组、筛选或提取月份中的某一天。

**参数**
+ `date expression`：日期表达式可以是文档中的日期字段、日期对象或日期字符串。

## 示例（MongoDB 外壳）
<a name="dayOfMonth-examples"></a>

此示例演示如何使用`$dayOfMonth`运算符从文档的日期字段中提取月份中的某一天。

**创建示例文档**

```
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") }
]);
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="dayOfMonth-code"></a>

要查看使用该`$dayOfMonth`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$dayOfWeek`运算符从给定的日期字段中提取一周中的某一天。它以 1（星期日）和 7（星期六）之间的数字返回一周中的某一天，这与 MongoDB 中的行为相同。

**参数**
+ `date field`: 要从中提取一周中的某天的日期字段。

## 示例（MongoDB 外壳）
<a name="dayOfWeek-examples"></a>

此示例演示如何使用`$dayOfWeek`运算符从`weather`集合中的`date`字段中提取星期几。

**创建示例文档**

```
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")
  }
]);
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="dayOfWeek-code"></a>

要查看使用该`$dayOfWeek`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$dayOfYear`运算符以 1 到 366 之间的数字返回日期的一年中的某一天（非闰年为 365）。

**参数**
+ `expression`：要从中提取一年中的某天的日期字段或表达式。

## 示例（MongoDB 外壳）
<a name="dayOfYear-examples"></a>

此示例演示如何使用`$dayOfYear`运算符从 Amazon DocumentDB 集合中的日期字段中提取一年中的某一天。

**创建示例文档**

```
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")
  }
])
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="dayOfYear-code"></a>

要查看使用该`$dayOfYear`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 聚合管道中的`$divide`运算符用于将一个数字除以另一个数字。它是对文档中的数值字段执行数学运算的有用运算符。

**参数**
+ `numerator`：股息或要分割的数字。
+ `denominator`: 除数或要除以的数字。

## 示例（MongoDB 外壳）
<a name="divide-examples"></a>

此示例演示如何使用`$divide`运算符根据员工的年薪和每年的工作时数计算员工的小时工资。

**创建示例文档**

```
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 }
]);
```

**查询示例**

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

**输出**

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

## 代码示例
<a name="divide-code"></a>

要查看使用该`$divide`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$eq`聚合运算符比较两个值，`true`如果它们相等，则返回，否则返回`false`。

**参数**
+ `expression1`：要比较的第一个值。
+ `expression2`: 第二个要比较的值。

## 示例（MongoDB 外壳）
<a name="eq-aggregation-examples"></a>

以下示例演示如何使用`$eq`运算符来检查产品数量是否与目标值匹配。

**创建示例文档**

```
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 }
]);
```

**查询示例**

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

**输出**

```
[
  { _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 }
]
```

## 代码示例
<a name="eq-aggregation-code"></a>

要查看使用`$eq`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$exp`运算符允许您将常数 e 提高到给定的数字。

**参数**
+ `expression`：要计算的表达式。这可以是任何有效的聚合表达式，包括字段引用、算术运算和其他聚合阶段。

## 示例（MongoDB 外壳）
<a name="exp-examples"></a>

以下示例演示如何使用`$exp`运算符来查找`quantity`字段大于该`price`字段的所有文档。

**创建示例文档**

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

**查询示例**

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

**输出**

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

## 代码示例
<a name="exp-code"></a>

要查看使用该`$exp`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$filter`运算符用于将筛选表达式应用于数组的每个元素，并返回一个仅包含符合指定条件的元素的数组。当您需要对文档中的数组字段执行复杂的筛选操作时，此运算符很有用。

**参数**
+ `input`: 要筛选的数组字段。
+ `as`：用于`cond`表达式中数组中每个`input`元素的变量名。
+ `cond`: 布尔表达式，用于确定是否应将给定元素包含在输出数组中。

## 示例（MongoDB 外壳）
<a name="filter-examples"></a>

以下示例演示如何使用`$filter`运算符来预测每个订单的客户，并创建一个新的数组字段 paidItems，其中仅包含价格大于 15 的 items 数组中的商品。从本质上讲，它会筛选每个订单的商品，仅包括价格超过15的产品。

**创建示例文档**

```
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 }
  ]}
]);
```

**查询示例**

```
db.orders.aggregate([
  {
    $project: {
      customer: 1,
      paidItems: {
        $filter: {
          input: "$items",
          as: "item",
          cond: { $gt: ["$$item.price", 15] }
        }
      }
    }
  }
]).pretty();
```

**输出**

```
[
  {
    _id: 1,
    customer: 'abc123',
    paidItems: [ { name: 'Product B', price: 20, qty: 1 } ]
  },
  { _id: 2, customer: 'def456', paidItems: [] },
  { _id: 3, customer: 'ghi789', paidItems: [] }
]
```

## 代码示例
<a name="filter-code"></a>

要查看使用该`$filter`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

5.0 版的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的`$first`操作员返回一组分组文档中的第一个文档。它通常在聚合管道中用来检索与特定条件匹配的第一个文档。

**参数**
+ `expression`：作为每个组中第一个值返回的表达式。

## 示例（MongoDB 外壳）
<a name="first-examples"></a>

以下示例演示如何使用`$first`运算符检索聚合期间每个类别遇到的第一个项目值。

注意：根据管道中文档的当前顺序`$first`返回第一个文档。为了确保特定的顺序（例如按日期、价格等），应在`$sort`舞台之前使用`$group`舞台。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.products.aggregate([
  { $group: { _id: "$category", firstItem: { $first: "$item" } } }
]);
```

**输出**

```
[
  { "_id" : "food", "firstItem" : "abc" },
  { "_id" : "toy", "firstItem" : "xyz" }
]
```

## 代码示例
<a name="first-code"></a>

要查看使用该`$first`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

Amazon DocumentDB 中的`$floor`运算符返回小于或等于指定数字的最大整数。此运算符对于向下舍入数值很有用。

**参数**
+ `expression`: 要向下舍入的数值表达式。

## 示例（MongoDB 外壳）
<a name="floor-examples"></a>

以下示例演示如何使用`$floor`运算符将十进制值向下舍入到最接近的整数。

**创建示例文档**

```
db.numbers.insertOne({ value: 3.14 });
```

**查询示例**

```
db.numbers.aggregate([
  { $project: { _id: 0, floored: { $floor: "$value" } } }
]);
```

**输出**

```
{ "floored" : 3 }
```

## 代码示例
<a name="floor-code"></a>

要查看使用该`$floor`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$geoNear`聚合阶段按接近指定点的顺序返回文档。它计算与该点的距离，并将该距离包括在输出文档中。

**参数**
+ `near`：计算距离的起点，指定为 geoJSON 或传统坐标。
+ `distanceField`：用于存储计算距离的字段名称。
+ `spherical`: 表示是否使用球面几何图形的布尔值（GeoJSON 点是必需的）。
+ `maxDistance`: 可选。距离中心点的最大距离。
+ `minDistance`: 可选。距离中心点的最小距离。
+ `query`: 可选。要应用的其他筛选条件。
+ `limit`: 可选。要返回的最大文档数。
+ `key`: 可选。存在多个地理空间索引时用于地理空间查询的字段。

## 示例（MongoDB 外壳）
<a name="geoNear-examples"></a>

以下示例演示如何使用`$geoNear`舞台查找离给定位置最近的门店。

**创建示例文档**

```
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] } }
]);
```

**查询示例**

```
db.stores.aggregate([
  {
    $geoNear: {
      near: { type: "Point", coordinates: [-122.4, 37.8] },
      distanceField: "distance",
      spherical: true
    }
  }
]);
```

**输出**

```
[
  { _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 }
]
```

## 代码示例
<a name="geoNear-code"></a>

要查看使用`$geoNear`聚合阶段的代码示例，请选择要使用的语言对应的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$group`聚合阶段允许您按指定的表达式对文档进行分组，并对分组的数据执行各种累积操作。这对于诸如根据分组数据计算总计、平均值或其他统计数据之类的任务非常有用。

**参数**
+ `_id`：指定对输入文档进行分组时应采用的表达式。这可以是字段名、计算表达式或两者的组合。
+ `accumulator expressions`:（可选）应应用于分组数据的一个或多个累加器表达式。这些表达式使用上面提到的累加器运算符。

## 示例（MongoDB 外壳）
<a name="group-examples"></a>

以下示例按城市对客户进行分组，并计算每个城市的总订单金额。

**创建示例文档**

```
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 }] }
]);
```

**查询示例**

```
db.customers.aggregate([
  {
    $group: {
      _id: "$city",
      totalOrders: { $sum: { $sum: "$orders.amount" } }
    }
  }
]);
```

**输出**

```
[
  { _id: 'Chicago', totalOrders: 150 },
  { _id: 'Los Angeles', totalOrders: 450 },
  { _id: 'New York', totalOrders: 500 }
]
```

## 代码示例
<a name="group-code"></a>

要查看使用该`$group`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$gt`聚合运算符比较两个值，`true`如果第一个值大于第二个值，则返回，否则返回`false`。

**参数**
+ `expression1`：要比较的第一个值。
+ `expression2`: 第二个要比较的值。

## 示例（MongoDB 外壳）
<a name="gt-aggregation-examples"></a>

以下示例演示如何使用`$gt`运算符来识别超过价格阈值的产品。

**创建示例文档**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", price: 1200 },
  { _id: 2, name: "Mouse", price: 25 },
  { _id: 3, name: "Monitor", price: 400 }
]);
```

**查询示例**

```
db.products.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      expensive: { $gt: ["$price", 100] }
    }
  }
]);
```

**输出**

```
[
  { _id: 1, name: 'Laptop', price: 1200, expensive: true },
  { _id: 2, name: 'Mouse', price: 25, expensive: false },
  { _id: 3, name: 'Monitor', price: 400, expensive: true }
]
```

## 代码示例
<a name="gt-aggregation-code"></a>

要查看使用`$gt`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$gte`聚合运算符比较两个值，`true`如果第一个值大于或等于第二个值，则返回，否则返回`false`。

**参数**
+ `expression1`：要比较的第一个值。
+ `expression2`: 第二个要比较的值。

## 示例（MongoDB 外壳）
<a name="gte-aggregation-examples"></a>

以下示例演示如何使用`$gte`运算符来检查学生是否通过了考试。

**创建示例文档**

```
db.students.insertMany([
  { _id: 1, name: "Alice", score: 85 },
  { _id: 2, name: "Bob", score: 60 },
  { _id: 3, name: "Charlie", score: 72 }
]);
```

**查询示例**

```
db.students.aggregate([
  {
    $project: {
      name: 1,
      score: 1,
      passed: { $gte: ["$score", 70] }
    }
  }
]);
```

**输出**

```
[
  { _id: 1, name: 'Alice', score: 85, passed: true },
  { _id: 2, name: 'Bob', score: 60, passed: false },
  { _id: 3, name: 'Charlie', score: 72, passed: true }
]
```

## 代码示例
<a name="gte-aggregation-code"></a>

要查看使用`$gte`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

运`$hour`算符从日期或时间戳字段中提取小时部分。

**参数**
+ `dateExpression`：运算符的应用日期。这必须解析为有效的 BSON 日期（例如，像 \$1createdAt 这样的字段或日期文字）。

也可以按以下格式将参数指定为文档：

\$1日期:`&lt;dateExpression&gt;`，时区：`&lt;timezoneExpression&gt;`\$1

这允许应用时区感知日期操作。

```
- `<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.
```

## 示例（MongoDB 外壳）
<a name="hour-examples"></a>

以下示例演示如何使用`$hour`运算符从日期字段中提取小时分量并相应地对数据进行分组。

**创建示例文档**

```
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") }
]);
```

**查询示例**

```
db.events.aggregate([
  {
    $project: {
      hour: { $hour: "$timestamp" }
    }
  },
  {
    $group: {
      _id: "$hour",
      count: { $sum: 1 }
    }
  },
  {
    $sort: { _id: 1 }
  }
]);
```

**输出**

```
[
  { "_id": 8, "count": 1 },
  { "_id": 10, "count": 1 },
  { "_id": 12, "count": 1 },
  { "_id": 16, "count": 1 },
  { "_id": 23, "count": 1 }
]
```

此查询按`timestamp`字段的小时部分对事件进行分组，并计算每小时的事件数。

## 代码示例
<a name="hour-code"></a>

要查看使用该`$hour`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

如果输入表达式的计算结果为空或未定义，则该`$ifNull`运算符用于返回指定值。在您想要提供默认值或处理 null/undefined 案例的情况下，此运算符可能很有用。

**参数**
+ `expression`：要计算的表达式。
+ `replacement`：如果`<expression>`计算结果为 null 或未定义，则返回的值。

## 示例（MongoDB 外壳）
<a name="ifNull-examples"></a>

以下示例演示了当`name`字段为空或未定义时如何使用`$ifNull`运算符来提供默认值。

**创建示例文档**

```
db.users.insertMany([
  { _id: 1, name: "John" },
  { _id: 2, name: null },
  { _id: 3 }
]);
```

**查询示例**

```
db.users.aggregate([
  {
    $project: {
      _id: 1,
      name: { $ifNull: ["$name", "No Name"] }
    }
  }
]);
```

**输出**

```
[
  { "_id": 1, "name": "John" },
  { "_id": 2, "name": "No Name" },
  { "_id": 3, "name": "No Name" }
]
```

## 代码示例
<a name="ifNull-code"></a>

要查看使用该`$ifNull`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$in`聚合运算符检查数组中是否存在指定值。`true`如果在数组中找到该值，则返回，`false`否则返回。

**参数**
+ `value`：要搜索的值。
+ `array`: 要在其中搜索的数组。

## 示例（MongoDB 外壳）
<a name="in-aggregation-examples"></a>

以下示例演示如何使用`$in`操作员来检查每位员工的技能组合中是否存在特定技能。

**创建示例文档**

```
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"] }
]);
```

**查询示例**

```
db.employees.aggregate([
  {
    $project: {
      name: 1,
      hasPython: { $in: ["Python", "$skills"] }
    }
  }
]);
```

**输出**

```
[
  { _id: 1, name: 'Sarah', hasPython: true },
  { _id: 2, name: 'Mike', hasPython: false },
  { _id: 3, name: 'Emma', hasPython: true }
]
```

## 代码示例
<a name="in-aggregation-code"></a>

要查看使用`$in`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$indexOfArray`运算符用于查找数组中指定元素首次出现的索引。此运算符返回数组中第一个与指定值匹配的元素的从零开始的索引位置。如果未找到该值，则返回 -1。

**参数**
+ `array`: 要搜索的数组。
+ `value`：要在数组中搜索的值。
+ `start`:（可选）数组中开始搜索的位置。默认值是 0。

## 示例（MongoDB 外壳）
<a name="indexOfArray-examples"></a>

以下示例演示如何使用 \$1 indexOfArray 运算符查找每个文档在 “fruits” 数组中首次出现的元素 “mango” 的索引。

**创建示例文档**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry", "durian"] },
  { _id: 2, fruits: ["mango", "orange", "pineapple"] },
  { _id: 3, fruits: ["kiwi", "lemon", "mango"] }
]);
```

**查询示例**

```
db.collection.aggregate([
  {
    $project: {
      _id: 1,
      fruitIndex: { $indexOfArray: ["$fruits", "mango"] }
    }
  }
]);
```

**输出**

```
{ "_id" : 1, "fruitIndex" : 1 }
{ "_id" : 2, "fruitIndex" : 0 }
{ "_id" : 3, "fruitIndex" : 2 }
```

## 代码示例
<a name="indexOfArray-code"></a>

要查看使用该`$indexOfArray`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的 \$1 indexOfBytes 运算符用于根据字符的字节位置查找字符串中子字符串的起始索引。这在处理可能包含多字节字符（例如非拉丁语脚本中的字符）的文本数据时非常有用。

**参数**
+ `string`: 要搜索的输入字符串。
+ `substring`: 要在输入字符串中搜索的子字符串。
+ `[<start>]`:（可选）搜索的起始位置（从零开始）。如果未指定，则从字符串的开头开始搜索。

## 示例（MongoDB 外壳）
<a name="indexOfBytes-examples"></a>

以下示例演示如何使用在一组`$indexOfBytes`表示办公桌位置的字符串中查找第一个连字符的索引。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.people.aggregate([
  { $project: { stateLocation: { $indexOfBytes: ["$Desk", "-"] } } }
]);
```

**输出**

```
{ "_id" : 1, "stateLocation" : 11 }
{ "_id" : 2, "stateLocation" : 6 }
{ "_id" : 3, "stateLocation" : 7 }
{ "_id" : 4, "stateLocation" : 8 }
```

## 代码示例
<a name="indexOfBytes-code"></a>

要查看使用该`$indexOfBytes`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$indexOfCP`运算符用于以码点 (CP) 形式查找字符串表达式中指定子字符串首次出现的索引。这在解析和提取字符串字段中的内容时非常有用。

**参数**
+ `string expression`: 要搜索的字符串。
+ `substring`: 要搜索的子字符串。
+ `[<start>]`:（可选）开始搜索的位置（从零开始的索引）。默认值为 0。

## 示例（MongoDB 外壳）
<a name="indexOfCP-examples"></a>

在此示例中，我们使用`$indexOfCP`运算符在每个文档的 Desk 字段中查找首次出现的连字符的索引。

**创建示例文档**

```
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"}
])
```

**查询示例**

```
db.people.aggregate([
  { $project: { stateLocation: { $indexOfCP: [ "$Desk", "-"] } } }
])
```

**输出**

```
{ "_id" : 1, "stateLocation" : 10 }
{ "_id" : 2, "stateLocation" : 6 }
{ "_id" : 3, "stateLocation" : 7 }
{ "_id" : 4, "stateLocation" : 8 }
```

## 代码示例
<a name="indexOfCP-code"></a>

要查看使用该`$indexOfCP`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$indexStats`聚合阶段可以深入了解集合中索引的使用情况。此运算符允许您监控索引的访问模式，这可以帮助您就索引管理和优化做出明智的决策。

**参数**

无

## 示例（MongoDB 外壳）
<a name="indexStats-examples"></a>

以下示例演示如何使用`$indexStats`运算符来分析 Amazon DocumentDB 集合中的索引使用情况。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.grocery.aggregate([
  { $indexStats: {} }
]);
```

**输出**

```
[
  {
    "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")
    }
  }
]
```

在此示例中，`$indexStats`运算符显示自上次重置或服务器重启以来，`product_1`索引已被访问 5 次，索引已被访问 10 次。`_id_`

## 代码示例
<a name="indexStats-code"></a>

要查看使用该`$indexStats`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$isArray`运算符用于检查文档中的字段是否为数组。此运算符在聚合管道和条件表达式中可用于处理数组类型字段。

**参数**
+ `field`：用于检查它是否为数组的字段路径。

## 示例（MongoDB 外壳）
<a name="isArray-examples"></a>

此示例演示如何使用`$isArray`运算符来识别 “清单” 字段为数组的文档。

**创建示例文档**

```
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}]}
]);
```

**查询示例**

```
db.videos.aggregate([
  {
    $match: {
      $isArray: "$inventory"
    }
  },
  {
    $project: {
      _id: 1,
      name: 1,
      "inventory.location": 1,
      "inventory.count": 1
    }
  }
]).pretty();
```

**输出**

```
{
  "_id": 4,
  "name": "Bravemind",
  "inventory": [
    {
      "location": "Mason City",
      "count": 250
    },
    {
      "location": "Des Moines",
      "count": 1000
    },
    {
      "location": "Ames",
      "count": 500
    }
  ]
}
```

## 代码示例
<a name="isArray-code"></a>

要查看使用该`$isArray`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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()
```

------

# \$1 isoDayOf 周
<a name="isoDayOfWeek"></a>

Amazon DocumentDB 中的`$isoDayOfWeek`运算符以整数值形式返回某一日期的 ISO 一周中的某一天。ISO 周日期系统定义每周从星期一开始，到星期日结束，第 1 周是包含一年中第一个星期四的那一周。

**参数**
+ `expression`：要为其返回 ISO 一周中的某天的日期表达式。

## 示例（MongoDB 外壳）
<a name="isoDayOfWeek-examples"></a>

以下示例演示如何使用`$isoDayOfWeek`运算符检索一组事件文档的 ISO 一周中的某一天。

**创建示例文档**

```
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") }
]);
```

**查询示例**

```
db.events.aggregate([
  { $project: {
    _id: 1,
    eventDate: 1,
    isoDayOfWeek: { $isoDayOfWeek: "$eventDate" }
  }}
]);
```

**输出**

```
[
  { "_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 }
]
```

## 代码示例
<a name="isoDayOfWeek-code"></a>

要查看使用该`$isoDayOfWeek`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$isoWeek`运算符返回某个日期的 ISO 周数。ISO 周日期系统是一种对一年中的几周进行编号的方式，其中新年的第一周是包含该年第一个星期四的那一周。这与公历不同，在公历中，新年的第一周是包含1月1日的那一周。

**参数**

无

## 示例（MongoDB 外壳）
<a name="isoWeek-examples"></a>

以下示例演示如何使用`$isoWeek`运算符检索给定日期的 ISO 周数。

**创建示例文档**

```
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") }
])
```

**查询示例**

```
db.dates.aggregate([
  {
    $project: {
      _id: 1,
      isoWeek: { $isoWeek: "$date" }
    }
  }
])
```

**输出**

```
[
  { "_id": 1, "isoWeek": 52 },
  { "_id": 2, "isoWeek": 52 },
  { "_id": 3, "isoWeek": 1 }
]
```

## 代码示例
<a name="isoWeek-code"></a>

要查看使用该`$isoWeek`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$isoWeekYear`运算符返回给定日期的 ISO 8601 周年号。ISO 周年号与公历年的不同之处在于，周年可能与日历年不同，尤其是在年初和年底。

**参数**
+ `expression`：要返回 ISO 8601 周年号的日期表达式。

## 示例（MongoDB 外壳）
<a name="isoWeekYear-examples"></a>

此示例演示如何使用`$isoWeekYear`运算符检索事件集合中每个文档的日期字段的 ISO 8601 周年。

**创建示例文档**

```
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") }
]);
```

**查询示例**

```
db.events.aggregate([
  { $project: {
    name: 1,
    isoWeekYear: { $isoWeekYear: "$date" }
  }}
]);
```

**输出**

```
[
  { "_id" : 1, "name" : "Event 1", "isoWeekYear" : 2023 },
  { "_id" : 2, "name" : "Event 2", "isoWeekYear" : 2023 },
  { "_id" : 3, "name" : "Event 3", "isoWeekYear" : 2023 }
]
```

## 代码示例
<a name="isoWeekYear-code"></a>

要查看使用该`$isoWeekYear`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$last`运算符用于返回数组中符合查询条件的最后一个元素。它对于检索数组中满足特定条件的最新元素或最后一个元素特别有用。

**参数**
+ `expression`: 匹配数组元素的表达式。

## 示例（MongoDB 外壳）
<a name="last-examples"></a>

以下示例演示了如何将`$last`运算符与`$filter`结合使用，从满足特定条件的数组中检索最后一个元素（例如，主题是 “科学”）。

**创建示例文档**

```
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 }
    ]
  }
]);
```

**查询示例**

```
db.collection.aggregate([
    { $match: { name: "John" } },
    {
      $project: {
        name: 1,
        lastScienceScore: {
          $last: {
            $filter: {
              input: "$scores",
              as: "score",
              cond: { $eq: ["$$score.subject", "science"] }
            }
          }
        }
      }
    }
  ]);
```

**输出**

```
[
  {
    _id: 1,
    name: 'John',
    lastScienceScore: { subject: 'science', score: 90 }
  }
]
```

## 代码示例
<a name="last-code"></a>

要查看使用该`$last`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$let`运算符用于将变量绑定到值并在表达式中使用这些变量。它允许您定义局部变量，这些变量可以在聚合管道的同一阶段的后续表达式中使用。

**参数**
+ `vars`：定义要在表达式中使用的变量的对象。
+ `in`：使用 vars 参数中定义的变量的表达式。

## 示例（MongoDB 外壳）
<a name="let-examples"></a>

此示例演示如何使用运`$let`算符来计算矩形的面积。

**创建示例文档**

```
db.shapes.insertMany([
  { name: "Rectangle 1", length: 5, width: 3 },
  { name: "Rectangle 2", length: 7, width: 4 },
  { name: "Rectangle 3", length: 6, width: 2 }
]);
```

**查询示例**

```
db.shapes.aggregate([
  {
    $project: {
      name: 1,
      area: {
        $let: {
          vars: {
            length: "$length",
            width: "$width"
          },
          in: {
            $multiply: ["$$length", "$$width"]
          }
        }
      }
    }
  }
])
```

**输出**

```
[
  {
    "_id": ObjectId("6161e5b1a3eba3c7f2960d03"),
    "name": "Rectangle 1",
    "area": 15
  },
  {
    "_id": ObjectId("6161e5b1a3eba3c7f2960d04"),
    "name": "Rectangle 2",
    "area": 28
  },
  {
    "_id": ObjectId("6161e5b1a3eba3c7f2960d05"),
    "name": "Rectangle 3",
    "area": 12
  }
]
```

## 代码示例
<a name="let-code"></a>

要查看使用该`$let`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$limit`运算符用于限制查询返回的文档数量。它与 M `$limit` ongoDB 运算符类似，但是在将其与亚马逊 DocumentDB 一起使用时需要考虑一些特定的注意事项。

在 Amazon DocumentDB 中，`$limit`运算符对于分页很有用，您想检索所有匹配文档的子集。它允许您控制每次响应中返回的文档数量，从而提高性能并减少通过网络传输的数据量。

**参数**
+ `limit`：要返回的最大文档数。这必须是一个非负整数值。

## 示例（MongoDB 外壳）
<a name="limit-examples"></a>

以下示例演示如何使用`$limit`运算符返回最多一个与给定过滤器匹配的文档。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.test.createIndex({ comments: "text" });

db.test.find({
  $and: [
    { star_rating: 5 },
    { $text: { $search: "couch" } }
  ]
}).limit(1);
```

**输出**

```
[ { _id: 2, star_rating: 5, comments: 'comfortable couch' } ]
```

## 代码示例
<a name="limit-code"></a>

要查看使用该`$limit`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$literal`运算符用于表示聚合管道阶段内的文字值。它允许您包含特定值，例如数字、字符串或布尔值，而无需将其解释为字段引用或表达式。

当您需要将文字值作为更复杂的聚合管道的一部分时，例如在构建动态查询筛选器或执行计算时，此运算符特别有用。

**参数**

无

## 示例（MongoDB 外壳）
<a name="literal-examples"></a>

以下示例演示了如何使用`$literal`运算符在聚合管道中包含文字值。该`$literal`运算符用于将值 18 作为文字值包含在 \$1gt 表达式中。这允许聚合管道将年龄字段与字面值 18 进行比较，以确定该人是否为成年人。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.collection.aggregate([
  {
    $project: {
      name: 1,
      age: 1,
      city: 1,
      isAdult: { $gt: ["$age", { $literal: 18 }] }
    }
  }
]);
```

**输出**

```
[
  {
    "_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
  }
]
```

## 代码示例
<a name="literal-code"></a>

要查看使用该`$literal`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

Amazon DocumentDB 中的`$ln`运算符计算指定数字的自然对数（以 e 为底）。它将数字的对数返回到以 e 为底的对数。

**参数**
+ `expression`：要计算自然对数的数字。

## 示例（MongoDB 外壳）
<a name="ln-examples"></a>

以下示例演示如何使用运`$log`算符来计算数字的自然对数。

**创建示例文档**

```
db.numbers.insertMany([
  { _id: 1, value: 10 },
  { _id: 2, value: 100 },
  { _id: 3, value: 1000 }
]);
```

**查询示例**

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

**输出**

```
[
  { "_id" : 1, "naturalLog" : 2.302585092994046 },
  { "_id" : 2, "naturalLog" : 4.605170185988092 },
  { "_id" : 3, "naturalLog" : 6.907755278982137 }
]
```

## 代码示例
<a name="ln-code"></a>

要查看使用该`$ln`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

Amazon DocumentDB 中的`$log`运算符计算数字的自然对数。它返回指定数字的以 e 为底的对数。

**参数**
+ `expression`：要计算自然对数的数字。
+ `base`：计算对数的基值。

## 示例（MongoDB 外壳）
<a name="log-examples"></a>

以下示例演示如何使用运`$log`算符来计算数字的自然对数。

**创建示例文档**

```
db.numbers.insertMany([
  { _id: 1, value: 10 },
  { _id: 2, value: 100 },
  { _id: 3, value: 1000 }
]);
```

**查询示例**

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

**输出**

```
[
  { "_id" : 1, "naturalLog" : 1 },
  { "_id" : 2, "naturalLog" : 2 },
  { "_id" : 3, "naturalLog" : 2.9999999999999996 }
]
```

## 代码示例
<a name="log-code"></a>

要查看使用该`$log`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

Amazon DocumentDB 中的`$log10`运算符用于计算数字以 10 为底的对数。它对于对聚合管道中的数值字段执行对数计算很有用。

**参数**
+ `expression`：要计算以 10 为底的对数的数值表达式。

## 示例（MongoDB 外壳）
<a name="log10-examples"></a>

以下示例演示如何使用`$log10`运算符计算数值字段以 10 为底的对数。

**创建示例文档**

```
db.numbers.insertMany([
  { _id: 1, value: 1 },
  { _id: 2, value: 10 },
  { _id: 3, value: 100 },
  { _id: 4, value: 1000 }
]);
```

**查询示例**

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

**输出**

```
[
  { "_id": 1, "log10Value": 0 },
  { "_id": 2, "log10Value": 1 },
  { "_id": 3, "log10Value": 2 },
  { "_id": 4, "log10Value": 3 }
]
```

## 代码示例
<a name="log10-code"></a>

要查看使用该`$log10`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$lt`聚合运算符比较两个值，`true`如果第一个值小于第二个值，则返回，否则返回`false`。

**参数**
+ `expression1`：要比较的第一个值。
+ `expression2`: 第二个要比较的值。

## 示例（MongoDB 外壳）
<a name="lt-aggregation-examples"></a>

以下示例演示如何使用`$lt`运算符识别低库存商品。

**创建示例文档**

```
db.warehouse.insertMany([
  { _id: 1, item: "Bolts", stock: 5 },
  { _id: 2, item: "Nuts", stock: 25 },
  { _id: 3, item: "Screws", stock: 8 }
]);
```

**查询示例**

```
db.warehouse.aggregate([
  {
    $project: {
      item: 1,
      stock: 1,
      lowStock: { $lt: ["$stock", 10] }
    }
  }
]);
```

**输出**

```
[
  { _id: 1, item: 'Bolts', stock: 5, lowStock: true },
  { _id: 2, item: 'Nuts', stock: 25, lowStock: false },
  { _id: 3, item: 'Screws', stock: 8, lowStock: true }
]
```

## 代码示例
<a name="lt-aggregation-code"></a>

要查看使用`$lt`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$lte`聚合运算符比较两个值，`true`如果第一个值小于或等于第二个值，则返回，否则返回`false`。

**参数**
+ `expression1`：要比较的第一个值。
+ `expression2`: 第二个要比较的值。

## 示例（MongoDB 外壳）
<a name="lte-aggregation-examples"></a>

以下示例演示如何使用`$lte`运算符来识别经济实惠的项目。

**创建示例文档**

```
db.menu.insertMany([
  { _id: 1, dish: "Salad", price: 8 },
  { _id: 2, dish: "Pasta", price: 12 },
  { _id: 3, dish: "Soup", price: 6 }
]);
```

**查询示例**

```
db.menu.aggregate([
  {
    $project: {
      dish: 1,
      price: 1,
      affordable: { $lte: ["$price", 10] }
    }
  }
]);
```

**输出**

```
[
  { _id: 1, dish: 'Salad', price: 8, affordable: true },
  { _id: 2, dish: 'Pasta', price: 12, affordable: false },
  { _id: 3, dish: 'Soup', price: 6, affordable: true }
]
```

## 代码示例
<a name="lte-aggregation-code"></a>

要查看使用`$lte`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$lookup`聚合阶段允许您在两个集合之间执行左外连接。此操作允许您根据匹配的字段值合并来自多个集合的数据。当您需要将来自相关集合的数据合并到查询结果中时，它特别有用。

**参数**
+ `from`：用于执行连接的集合的名称。
+ `localField`：输入文档中要与之匹配的字段`foreignField`。
+ `foreignField`: `from` 集合中文档中要与之匹配的字段`localField`。
+ `as`：要添加到包含`from`集合中匹配文档的输出文档的新字段的名称。

## 示例（MongoDB 外壳）
<a name="lookup-examples"></a>

以下示例演示了将集合中的数据联接到`orders`集合中的`customers`简单`$lookup`操作。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.customers.aggregate([
  {
    $lookup: {
      from: "orders",           
      localField: "_id",        
      foreignField: "customer_id", 
      as: "orders" 
    }
  }
]);
```

**输出**

```
[
  {
    _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 } ]
  }
]
```

## 代码示例
<a name="lookup-code"></a>

要查看使用该`$lookup`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的`$ltrim`运算符用于从字符串中删除前导字符。默认情况下，它会删除前导空格字符，但您也可以通过传递 chars 参数来指定一组要删除的字符。

**参数**
+ `input`：要从中删除前导空格字符的输入字符串。
+ `chars`:（可选）删除特定字符。

## 示例（MongoDB 外壳）
<a name="ltrim-examples"></a>

以下示例演示了从字符串开头删除指定字符 (” \$1”) 的用法。`$ltrim`

**创建示例文档**

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

**查询示例**

```
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      name: {
        $ltrim: { input: "$name", chars: " *" }  
      },
      age: 1
    }
  }
]);
```

**输出**

```
[
  { "name": "John Doe", "age": 30 },
  { "name": "Jane Doe ", "age": 25 },
  { "name": "Bob Smith  ", "age": 35 }
]
```

## 代码示例
<a name="ltrim-code"></a>

要查看使用该`$ltrim`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$map`运算符允许您将指定的表达式应用于数组中的每个元素，并返回包含已转换元素的新数组。此运算符对于操作和转换数组中的数据特别有用，它可以将数组处理推到数据库级别，从而帮助简化应用程序代码并提高查询性能。

**参数**
+ `input`: 要转换的数组。
+ `as`:（可选）在 in 表达式中用于表示当前正在处理的元素的变量的名称。
+ `in`: 要应用于输入数组中每个元素的表达式。

## 示例（MongoDB 外壳）
<a name="map-examples"></a>

以下示例演示如何使用 \$1map 运算符来转换数字数组，将每个值加倍。

**创建示例文档**

```
db.collection.insertMany([
  { _id: 1, numbers: [1, 2, 3, 4, 5] },
  { _id: 2, numbers: [10, 20, 30, 40, 50] }
])
```

**查询示例**

```
db.collection.aggregate([
  {
    $project: {
      doubledNumbers: { $map: { input: "$numbers", as: "num", in: { $multiply: ["$$num", 2] } } }
    }
  }
])
```

**输出**

```
[
  { _id: 1, doubledNumbers: [2, 4, 6, 8, 10] },
  { _id: 2, doubledNumbers: [20, 40, 60, 80, 100] }
]
```

## 代码示例
<a name="map-code"></a>

要查看使用该`$map`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$match`管道阶段用于筛选输入文档，仅筛选符合指定查询条件的文档。它是聚合操作中最常用的流水线阶段之一。该`$match`阶段在任何其他管道阶段之前应用，使您可以有效地减少后续阶段需要处理的文档数量。

**参数**
+ `query`: 一份表达行动选择标准的文件。查询文档使用与`find()`方法相同的语法。

## 示例（MongoDB 外壳）
<a name="match-examples"></a>

以下示例演示如何使用`$match`舞台根据特定字段值筛选文档。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.collection.aggregate([
  { $match: { age: { $gt: 30 } } },
  { $project: { _id: 1, name: 1, city: 1 } }
]);
```

**输出**

```
[
  { "_id": 3, "name": "Bob", "city": "Chicago" },
  { "_id": 4, "name": "Alice", "city": "Miami" }
]
```

该`$match`阶段会筛选文档，使其仅包括`age`字段大于 30 的文档。

## 代码示例
<a name="match-code"></a>

要查看使用该`$match`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$max`聚合阶段用于返回管道阶段中所有文档中指定字段的最大值。此运算符对于查找一组文档中的最大值很有用。

**参数**
+ `expression`：用于计算最大值的表达式。

## 示例（MongoDB 外壳）
<a name="max-examples"></a>

以下示例演示如何使用`$max`运算符在一组学生文档中查找最高分数。该`$group`阶段将所有文档组合在一起，`$max`运算符用于计算所有文档中该`score`字段的最大值。

**创建示例文档**

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

**查询示例**

```
db.students.aggregate([
  { $group: { _id: null, maxScore: { $max: "$score" } } },
  { $project: { _id: 0, maxScore: 1 } }
])
```

**输出**

```
[ { maxScore: 92 } ]
```

## 代码示例
<a name="max-code"></a>

要查看使用该`$max`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$meta`聚合运算符访问与聚合管道中的文档关联的元数据。它通常用于检索文本搜索分数和按相关性对结果进行排序。

**参数**
+ `textScore`：检索文本搜索分数，该分数表示文档与搜索查询的相关性。

## 示例（MongoDB 外壳）
<a name="meta-aggregation-examples"></a>

以下示例演示了在聚合管道中使用`$meta`运算符来检索文本搜索分数并按文本搜索分数进行排序。

**创建示例文档**

```
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." }
]);
```

**查询示例**

```
db.articles.aggregate([
  { $match: { $text: { $search: "Python" } } },
  { $addFields: { score: { $meta: "textScore" } } },
  { $sort: { score: -1 } }
]);
```

**输出**

```
[
  {
    _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
  }
]
```

## 代码示例
<a name="meta-aggregation-code"></a>

要查看使用`$meta`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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()
```

------

# merge
<a name="merge"></a>

在 8.0 中引入

Amazon DocumentDB 中的`$merge`聚合阶段用于将前一个管道阶段的结果合并到目标集合中。这对于根据输入文档中的数据在目标集合中更新或插入文档非常有用。

该`$merge`阶段允许您根据输入文档和目标集合之间的匹配条件执行各种操作，例如：

```
- Insert new documents
- Update existing documents
- Delete documents
- Fail the operation if there are any conflicts
```

**参数**
+ `into`:（必填）要将输入文档合并到的目标集合的名称。
+ `on`:（必填）用作输入文档和目标集合之间匹配条件的字段。
+ `whenMatched`:（可选）当输入文档与目标集合中的现有文档相匹配时要执行的操作。支持的值为：`"merge"`、`"replace"`、`"keepExisting"` 和 `"fail"`。
+ `whenNotMatched`:（可选）当输入文档与目标集合中的任何文档都不匹配时要执行的操作。支持的值为：`"insert"`和`"fail"`。

## 示例（MongoDB 外壳）
<a name="merge-examples"></a>

以下示例演示如何使用`$merge`舞台使用来自输入管道的新数据更新`users`集合。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.inputData.aggregate([
  {
    $merge: {
      into: "users",
      on: "_id",
      whenMatched: "merge",
      whenNotMatched: "insert"
    }
  }
])
```

**输出**

运行`$merge`管道后，该`users`集合将包含以下文档：

```
[
  { _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" }
]
```

## 代码示例
<a name="merge-code"></a>

要查看使用该`$merge`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是在 Node.js 应用程序中使用 \$1merge 运算符的示例：

```
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 ]

以下是在 Python 应用程序中使用 \$1merge 运算符的示例：

```
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>

Amazon DocumentDB 中的`$mergeObjects`运算符用于将多个文档或对象合并为一个文档。当您需要合并两个或多个文档或对象的内容时，此运算符特别有用，这可能会将一个对象的值与另一个对象的值覆盖。

**参数**
+ `expression1`: 第一个要合并的对象。
+ `expression2`:（可选）要合并的第二个对象。
+ `expression3`:（可选）要合并的其他对象。

## 示例（MongoDB 外壳）
<a name="mergeObjects-examples"></a>

以下示例演示如何使用`$mergeObjects`运算符组合两个对象。

**创建示例文档**

```
db.collection.insertMany([
  { "_id": 1, "name": "John", "address": { "city": "New York", "state": "NY" } },
  { "_id": 2, "name": "Jane", "address": { "city": "Los Angeles", "state": "CA" } }
]);
```

**查询示例**

```
db.collection.aggregate([
  {
    $project: {
      "combinedAddress": {
        $mergeObjects: ["$address", { "country": "USA" }]
      }
    }
  }
])
```

**输出**

```
[
  {
    "_id": 1,
    "combinedAddress": {
      "city": "New York",
      "state": "NY",
      "country": "USA"
    }
  },
  {
    "_id": 2,
    "combinedAddress": {
      "city": "Los Angeles",
      "state": "CA",
      "country": "USA"
    }
  }
]
```

## 代码示例
<a name="mergeObjects-code"></a>

要查看使用该`$mergeObjects`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$millisecond`运算符用于提取日期值的毫秒部分。

**参数**

无

## 示例（MongoDB 外壳）
<a name="millisecond-examples"></a>

此示例演示如何使用`$millisecond`运算符提取日期值的毫秒部分。

**创建示例文档**

```
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")
  }
])
```

**查询示例**

```
db.events.aggregate([
  {
    $project: {
      name: 1,
      milliseconds: { $millisecond: "$timestamp" }
    }
  }
])
```

**输出**

```
[
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c1"),
    "name": "Event 1",
    "milliseconds": 123
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c2"),
    "name": "Event 2",
    "milliseconds": 456
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c3"),
    "name": "Event 3",
    "milliseconds": 789
  }
]
```

## 代码示例
<a name="millisecond-code"></a>

要查看使用该`$millisecond`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

运`$min`算符返回值数组中的最小值。它可以在聚合阶段用于在多个文档中查找指定字段的最小值。

**参数**
+ `expression`：要计算的表达式。这可以是字段路径、变量或任何解析为值的表达式。

## 示例（MongoDB 外壳）
<a name="min-examples"></a>

以下示例演示如何使用`$min`运算符在多个文档中查找该`age`字段的最小值。

**创建示例文档**

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

**查询示例**

```
db.users.aggregate([
  { $group: { _id: null, minAge: { $min: "$age" } } },
  { $project: { _id: 0, minAge: 1 } }
])
```

**输出**

```
[ { minAge: 28 } ]
```

## 代码示例
<a name="min-code"></a>

要查看使用该`$min`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$minute`聚合管道阶段从日期或时间戳字段中提取分钟值。

当您需要在聚合管道中执行基于日期和时间的计算或分组时，此运算符很有用。

**参数**
+ `expression`：要从中提取分钟值的日期或时间戳字段。

## 示例（MongoDB 外壳）
<a name="minute-examples"></a>

以下示例演示如何使用`$minute`运算符按从时间戳字段中提取的分钟值对文档进行分组，并计算每组中的文档数量。

**创建示例文档**

```
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") }
]);
```

**查询示例**

```
db.events.aggregate([
  {
    $group: {
      _id: {
        minute: { $minute: "$timestamp" }
      },
      count: { $count: {} }
    }
  },
  { $sort: { "_id.minute": 1 } }
]);
```

**输出**

```
[
  { "_id": { "minute": 30 }, "count": 2 },
  { "_id": { "minute": 31 }, "count": 2 },
  { "_id": { "minute": 32 }, "count": 1 }
]
```

## 代码示例
<a name="minute-code"></a>

要查看使用该`$minute`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

运算`$mod`符是一种对数字执行模运算的算术运算符。它返回一个数字除以另一个数的余数。此运算符通常用于确定一个数字是奇数还是偶数，或者将项目分配到有限数量的组中。

**参数**
+ `expression1`: 股息表达式。
+ `expression2`: 除数表达式。

## 示例（MongoDB 外壳）
<a name="mod-examples"></a>

此示例演示如何使用`$mod`运算符来确定在 100 个包裹中配送时剩余小部件的数量。

**创建示例文档**

```
db.widgets.insertMany([
  { "_id" : 1, "widget" : "A", "count" : 80372 },
  { "_id" : 2, "widget" : "B", "count" : 409282 },
  { "_id" : 3, "widget" : "C", "count" : 60739 }
])
```

**查询示例**

```
db.widgets.aggregate([
  { $addFields: { leftOver: { $mod: [ "$count", 100 ] } } }
])
```

**输出**

```
[
  { "_id" : 1, "widget" : "A", "count" : 80372, "leftOver" : 72 },
  { "_id" : 2, "widget" : "B", "count" : 409282, "leftOver" : 82 },
  { "_id" : 3, "widget" : "C", "count" : 60739, "leftOver" : 39 }
]
```

输出显示每个文档的剩余部分`count`除以 100，这表示以 100 的包裹配送时剩余的小部件数量。

## 代码示例
<a name="mod-code"></a>

要查看使用该`$mod`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$month`运算符以 1 到 12 之间的数字返回日期的月份。此运算符对于从日期字段中提取月份组成部分以及执行基于日期的聚合和分析非常有用。

**参数**
+ `date_expression`：这是包含要从中提取月份的日期或时间戳的表达式或字段。

## 示例（MongoDB 外壳）
<a name="month-examples"></a>

以下示例演示如何使用`$month`运算符从日期字段中提取月份并按月对数据进行分组。

**创建示例文档**

```
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") }
]);
```

**查询示例**

```
db.sales.aggregate([
  { $group: { 
      _id: { month: { $month: "$date" } },
      totalSales: { $sum: "$price" }
    }},
  { $sort: { "_id.month": 1 } }
]);
```

**输出**

```
[
  { _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 }
]
```

## 代码示例
<a name="month-code"></a>

要查看使用该`$month`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$multiply`运算符用于将两个或多个字段或表达式的值相乘。此运算符对于对文档中的数值字段执行算术运算特别有用。它可以用于聚合管道的各个阶段，例如`$project`和`$addFields`，以创建新字段或修改现有字段。

**参数**
+ `expression1`：第一个要相乘的数值表达式。
+ `expression2`: 第二个要相乘的数值表达式。
+ `[expression3, ...]`:（可选）要相乘的其他数值表达式。

## 示例（MongoDB 外壳）
<a name="multiply-examples"></a>

以下示例演示了`$multiply`使用信用卡`bonus_rate`进行行程的客户使用`bonus_miles`乘法`base_miles`和进行计算。

**示例文档**

```
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 }
]);
```

**查询示例**

```
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"]
      }
    }
  }
]);
```

**输出**

```
[
  { _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 }
]
```

## 代码示例
<a name="multiply-code"></a>

要查看使用该`$multiply`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$natural`运算符用于按自然顺序对文档进行排序，也就是文档在集合中的插入顺序。这与默认的排序行为形成鲜明对比，默认排序行为是根据指定字段的值对文档进行排序。

**参数**

无

## 示例（MongoDB 外壳）
<a name="natural-examples"></a>

以下示例演示如何使用`$natural`运算符按自然顺序对集合中的文档进行排序。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.people.find({}, { "_id": 1, "name": 1 }).sort({ "$natural": 1 });
```

**输出**

```
[
  { "_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" }
]
```

该查询按自然顺序（即插入顺序）对集合中的文档进行排序。

## 代码示例
<a name="natural-code"></a>

要查看使用该`$natural`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$ne`聚合运算符比较两个值，`true`如果两个值不相等，则返回，否则返回`false`。

**参数**
+ `expression1`：要比较的第一个值。
+ `expression2`: 第二个要比较的值。

## 示例（MongoDB 外壳）
<a name="ne-aggregation-examples"></a>

以下示例演示如何使用`$ne`运算符来识别状态发生变化的订单。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      status: 1,
      expectedStatus: 1,
      needsAttention: { $ne: ["$status", "$expectedStatus"] }
    }
  }
]);
```

**输出**

```
[
  { _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 }
]
```

## 代码示例
<a name="ne-aggregation-code"></a>

要查看使用`$ne`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$not`聚合运算符对表达式执行逻辑 NOT 运算。`true`如果表达式的计算结果为`false`，如果表达式的计算结果为，`false`则返回。`true`

**参数**
+ `expression`: 要否定的表达式。

## 示例（MongoDB 外壳）
<a name="not-aggregation-examples"></a>

以下示例演示如何使用`$not`运算符反转布尔值。

**创建示例文档**

```
db.users.insertMany([
  { _id: 1, name: "Alice", active: true },
  { _id: 2, name: "Bob", active: false },
  { _id: 3, name: "Charlie", active: true }
]);
```

**查询示例**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      active: 1,
      inactive: { $not: ["$active"] }
    }
  }
]);
```

**输出**

```
[
  { _id: 1, name: 'Alice', active: true, inactive: false },
  { _id: 2, name: 'Bob', active: false, inactive: true },
  { _id: 3, name: 'Charlie', active: true, inactive: false }
]
```

## 代码示例
<a name="not-aggregation-code"></a>

要查看使用`$not`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$objectToArray`聚合运算符将对象（或文档）转换为数组。运算符的输入是一个文档，输出由输入文档中每个字段值对的数组元素组成。当您需要将文档的各个字段作为数组处理时，例如要查找具有特定字段最大值或最小值的文档时，此运算符很有用。

**参数**
+ `expression`: 要转换为数组的文档表达式。

## 示例（MongoDB 外壳）
<a name="objectToArray-examples"></a>

以下示例演示了如何使用`$objectToArray`操作员来查找视频租赁连锁店的最大库存量的文档。

**创建示例文档**

```
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
    }
  }
]);
```

**查询示例**

```
db.videos.aggregate([
  {
    $project: {
      name: 1,
      videos: {
        $objectToArray: "$inventory"
      }
    }
  },
  {
    $unwind: "$videos"
  },
  {
    $group: {
      _id: "$name",
      maxInventory: {
        $max: "$videos.v"
      }
    }
  }
]);
```

**输出**

```
[
  {
    "_id": "Bravemind",
    "maxInventory": 1000
  },
  {
    "_id": "Live Soft",
    "maxInventory": 1000
  },
  {
    "_id": "Romancing the Rock",
    "maxInventory": 500
  },
  {
    "_id": "Top Pilot",
    "maxInventory": 1000
  }
]
```

## 代码示例
<a name="objectToArray-code"></a>

要查看使用该`$objectToArray`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$or`聚合运算符计算多个表达式，`true`如果至少有一个表达式的计算结果为，则返回。`true``false`仅当所有表达式均为时，它才会返回`false`。

**参数**
+ `expressions`：要计算的表达式数组。

## 示例（MongoDB 外壳）
<a name="or-aggregation-examples"></a>

以下示例演示如何使用`$or`运算符来检查产品是否符合多个条件中的任何一个。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.items.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      onSale: 1,
      goodDeal: {
        $or: [
          { $lt: ["$price", 50] },
          { $eq: ["$onSale", true] }
        ]
      }
    }
  }
]);
```

**输出**

```
[
  { _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 }
]
```

## 代码示例
<a name="or-aggregation-code"></a>

要查看使用`$or`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$out`运算符用于将聚合管道的结果写入指定的集合。

`$out`应该是最后一步。

**参数**
+ `output_collection`：要写入聚合结果的输出集合的名称。

**注意**：如果集合已经存在，则会将其替换为聚合阶段的结果。

## 示例（MongoDB 外壳）
<a name="out-examples"></a>

以下示例演示如何在 Amazon DocumentDB 中使用`$out`运算符将聚合管道的结果写入新集合。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.products.aggregate([
  { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
  { $out: "product_categories" }
])
```

**输出**

无（结果写入输出集合）。

聚合管道按类别对产品进行分组，并计算每个类别的商品总价。`$out`操作员将结果写入名为 “product\$1categories” 的新集合。

**要查看输出集合中的结果，请执行以下操作：**

```
db.product_categories.find()
[
{ "_id" : "Books", "totalPrice" : 125 },
{ "_id" : "Electronics", "totalPrice" : 300 }
]
```

## 代码示例
<a name="out-code"></a>

要查看使用该`$out`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

在 8.0 中引入

Amazon DocumentDB 中的`$pow`运算符允许您将数字提高为次方。这对于在聚合管道中执行指数计算非常有用。

**参数**
+ `<number>`（必填）：要提高为次的数字。
+ `<exponent>`（必填）：应将数字提高到的次方。

## 示例（MongoDB 外壳）
<a name="pow-examples"></a>

以下示例演示如何使用`$pow`运算符计算数字的平方。

**创建示例文档**

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

**查询示例**

```
db.numbers.aggregate([
  { $addFields: { "square": { $pow: ["$value", 2] } } }
])
```

**输出**

```
[
  { "_id": 1, "value": 2, "square": 4 },
  { "_id": 2, "value": 3, "square": 9 },
  { "_id": 3, "value": 4, "square": 16 }
]
```

## 代码示例
<a name="pow-code"></a>

要查看使用该`$pow`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是在 Node.js 应用程序中使用 \$1pow 运算符的示例：

```
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 ]

以下是在 Python 应用程序中使用 \$1pow 运算符的示例：

```
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>

`$push`聚合运算符为每个组返回一个包含指定表达式中所有值的数组。它通常在`$group`舞台中用于将值累积到数组中。

**参数**
+ `expression`：要为组中的每个文档计算的表达式。

## 示例（MongoDB 外壳）
<a name="push-aggregation-examples"></a>

以下示例演示如何使用`$push`运算符收集每个类别的所有产品名称。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.sales.aggregate([
  {
    $group: {
      _id: "$category",
      products: { $push: "$product" }
    }
  }
]);
```

**输出**

```
[
  { _id: 'Furniture', products: [ 'Desk', 'Chair' ] },
  { _id: 'Electronics', products: [ 'Laptop', 'Mouse', 'Keyboard' ] }
]
```

## 代码示例
<a name="push-aggregation-code"></a>

要查看使用`$push`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$project`运算符允许您有选择地在输出文档中包含或排除字段，将值传递到下一个管道阶段，以及从输入文档值中计算新字段。

**参数**
+ `field`: 要在输出文档中包含或排除的字段，它可以是字段路径（例如，“a.b.c”）。
+ `1`或`true`：在输出中包含该字段。
+ `0`或`false`：从输出中排除该字段。

## 示例（MongoDB 外壳）
<a name="project-examples"></a>

以下示例演示了`$project`运算符在学生集合中的用法

**创建示例文档**

```
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" }
  ]);
```

此查询仅在输出中包含`name`和`math`字段。除非明确排除，否则默认情况下会包含该`_id`字段。

```
db.students.aggregate([
  { $project: { "name": 1, "math": 1 } }
])
```

**输出**

```
{ _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 }
```

此查询从输出中排除`grade`和`_id`字段，显示所有其他字段（`name`、`math`、`science`）。

```
db.students.aggregate([
  { $project: { "grade": 0, "_id": 0 } }
])
```

**输出**

```
{ 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 }
```

## 代码示例
<a name="project-code"></a>

要查看使用该`$project`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

8.0 版的新增内容

Amazon DocumentDB 中的`$rand`运算符用于生成 0 到 1 之间的随机数。

**参数**

无

## 示例（MongoDB 外壳）
<a name="rand-examples"></a>

以下示例演示如何使用`$rand`运算符从`temp`集合中随机选择两个文档。

**创建示例文档**

```
db.items.insertMany([
  { "name": "pencil", "quantity": 110 },
  { "name": "pen", "quantity": 159 }
])
```

**查询示例**

```
db.items.aggregate([
  {
    $project: {
      randomValue: { $rand: {} }
    }
  }
])
```

**输出**

```
[
  {
    _id: ObjectId('6924a5edd66dcae121d29517'),
    randomValue: 0.8615243955294392
  },
  {
    _id: ObjectId('6924a5edd66dcae121d29518'),
    randomValue: 0.22815483022099903
  }
]
```

## 代码示例
<a name="rand-code"></a>

要查看使用该`$rand`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$range`聚合运算符用于创建指定范围内连续数字的数组。该运算符对于生成数字序列特别有用，例如比赛中援助站的英里标记，如以下示例所示。

**参数**
+ `start`：范围的起始值。
+ `end`：范围的结束值。
+ `step`:（可选）生成范围时要使用的步长值。如果未提供，则默认步长值为 1。

## 示例（MongoDB 外壳）
<a name="range-examples"></a>

在此示例中，我们将使用`$range`运算符生成自行车比赛中供水站的英里标记。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.races.aggregate([
  {
    $project: {
      race: 1,
      "waterStations": { $range: [20, "$distance", 20] }
    }
  }
]);
```

**输出**

```
[
  {
    _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 ] }
]
```

## 代码示例
<a name="range-code"></a>

要查看使用该`$range`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$redact`聚合阶段用于根据指定字段的值有选择地在输出文档中包含或排除内容。这在需要根据访问级别或用户权限控制敏感数据可见性的场景中特别有用。

**参数**
+ `$cond`：文档中每个字段的计算结果为`$$KEEP``$$PRUNE`、或`$$DESCEND`的表达式。
+ `$$KEEP`：保留输出文档中的当前字段。
+ `$$PRUNE`：从输出文档中移除当前字段。
+ `$$DESCEND`: 以递归方式将`$redact`舞台应用于当前字段，即对象或数组。

## 示例（MongoDB 外壳）
<a name="redact-examples"></a>

在此示例中，我们将使用`$redact`舞台根据订单的状态筛选订单，仅显示具有特定状态值的订单。

**创建示例文档**

```
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" }
])
```

**查询示例**

```
db.orders.aggregate([
  {
    $redact: {
      $cond: {
        if: { $in: ["$status", ["shipped", "processing"]] },
        then: "$$KEEP",
        else: "$$PRUNE"
      }
    }
  }
])
```

**输出**

```
[
  { _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' }
]
```

在此示例中，`$redact`舞台检查每个文档中`status`字段的值。如果`status`是 “已发货” 或 “处理中”，则保留文档 (`$$KEEP`)。否则，文档将被修剪 () `$$PRUNE`。

## 代码示例
<a name="redact-code"></a>

要查看使用该`$redact`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$reduce`聚合运算符用于将包含两个参数的函数累积应用于数组的元素，以将数组缩减为单个值。对于在聚合管道中对数组数据执行复杂的计算或转换，此运算符特别有用。

**参数**
+ `input`: 要缩减的数组。
+ `initialValue`：要在还原操作中使用的初始值。
+ `in`：要对`input`数组的每个元素进行评估的表达式。此表达式应返回一个值，该值将在下一次缩减迭代中使用。

## 示例（MongoDB 外壳）
<a name="reduce-examples"></a>

以下示例演示如何使用`$reduce`运算符计算数组中所有元素的总和。

**创建示例文档**

```
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] }
])
```

**查询示例**

```
db.orders.aggregate([
  {
    $project: {
      total: {
        $reduce: {
          input: "$items",
          initialValue: 0,
          in: { $add: ["$$value", "$$this"] }
        }
      }
    }
  }
])
```

**输出**

```
[
  { "_id": 1, "total": 15 },
  { "_id": 2, "total": 60 },
  { "_id": 3, "total": 80 },
  { "_id": 4, "total": 300 }
]
```

运`$reduce`算符遍历`items`数组，将每个元素加到 0 中`initialValue`。结果是数组中所有元素的总和。

## 代码示例
<a name="reduce-code"></a>

要查看使用该`$reduce`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是在 Node.js 应用程序中使用`$reduce`运算符的示例：

```
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 ]

以下是在 python 应用程序中使用`$reduce`运算符的示例：

```
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>

5.0 版的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的`$regexFind`运算符用于对文档中的字符串字段执行正则表达式匹配。它允许您搜索和提取与给定正则表达式模式匹配的特定子字符串。

**参数**
+ `input`：要搜索的字符串字段或表达式。
+ `regex`：要匹配的正则表达式模式。
+ `options`:（可选）为正则表达式指定可选参数的对象，例如区分大小写和多行匹配。支持的选项有`i`（不区分大小写）和`m`（多行）。

## 示例（MongoDB 外壳）
<a name="regexFind-examples"></a>

以下示例演示如何使用`$regexFind`运算符搜索`name`字段与特定正则表达式模式匹配的文档。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.users.aggregate([
  {
    $project: {
      names: {
        $regexFind: { input: '$name', regex: 'j', options: 'i' }
      }
    }
  },
  { $match: {names: {$ne: null}}}
])
```

此查询将返回该`name`字段包含字母 “j”（不区分大小写）的所有文档。

**输出**

```
[
  { _id: 1, names: { match: 'J', idx: 0, captures: [] } }
]
```

**注意：**如果您的查询使用的是 Amazon DocumentDB 规划器版本 1，则必须使用提示才能使用索引。如果没有提示，查询可能会执行集合扫描。要查看您的计划程序版本并了解有关使用提示的更多信息，请参阅 [Amazon DocumentDB Query Planner 文档] (https://docs.aws.amazon.com/documentdb/latest/developerguide/query-planner.html)。

## 代码示例
<a name="regexFind-code"></a>

要查看使用该`$regexFind`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

在 5.0 中引入

Amazon DocumentDB 中的`$regexFindAll`运算符用于对文档中的字符串字段执行正则表达式匹配。它允许您搜索和提取与给定正则表达式模式匹配的特定子字符串，返回正则表达式的所有匹配项。

**参数**
+ `input`：要搜索的字符串字段或表达式。
+ `regex`：要匹配的正则表达式模式。
+ `options`:（可选）为正则表达式指定可选参数的对象，例如区分大小写和多行匹配。支持的选项有`i`（不区分大小写）和`m`（多行）。

## 示例（MongoDB 外壳）
<a name="regexFindAll-examples"></a>

以下示例演示如何使用`$regexFindAll`运算符从`email`字段中提取所有字母序列。

**创建示例文档**

```
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" }
  
]);
```

**查询示例**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      emailMatches: {
        $regexFindAll: { input: '$email', regex: '[a-z]+', options: 'i' }
      }
    }
  }
])
```

**输出**

```
[
  {
    _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: [] }
    ]
  }
]
```

**注意：**如果您的查询使用的是 Amazon DocumentDB 规划器版本 1，则必须使用提示才能使用索引。如果没有提示，查询可能会执行集合扫描。要查看您的计划程序版本并了解有关使用提示的更多信息，请参阅 [Amazon DocumentDB Query Planner 文档] (https://docs.aws.amazon.com/documentdb/latest/developerguide/query-planner.html)。

## 代码示例
<a name="regexFindAll-code"></a>

要查看使用该`$regexFindAll`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是在 Node.js 应用程序中使用`$regexFind`运算符的示例：

```
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 ]

以下是在 Python 应用程序中使用`$regexFind`运算符的示例：

```
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>

5.0 版的新增内容。弹性集群不支持。

Amazon DocumentDB 中的`$regexMatch`运算符用于对字符串字段执行正则表达式匹配。它返回一个布尔值（`true`或`false`），表示输入字符串是否与指定的模式匹配。

**参数**
+ `input`: 要根据正则表达式进行测试的字符串。
+ `regex`：要匹配的正则表达式模式。
+ `options`:（可选）用于修改正则表达式行为的标志，例如不区分大小写的匹配 (`i`) 或多行匹配 ()。`m`

## 示例（MongoDB 外壳）
<a name="regexMatch-examples"></a>

以下示例演示如何使用`$regexMatch`运算符来检查名称是否以字母 “M” 开头。运算符`false`为每个文档返回`true`或。

**创建示例文档**

```
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" },

]);
```

**查询示例**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      startsWithM: {
        $regexMatch: {
          input: "$name",
          regex: "^M",
          options: "i"
        }
      }
    }
  }
]);
```

**输出**

```
{ _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 }
```

## 代码示例
<a name="regexMatch-code"></a>

要查看使用该`$regexMatch`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

在 5.0 中引入

Amazon DocumentDB 中的`$replaceAll`运算符用于将字段中所有出现的指定字符串模式替换为新字符串。此运算符可用于数据标准化、文本清理和字符串操作等任务。

**参数**
+ `input`：包含要替换的字符串的字段或表达式。
+ `find`：要搜索和替换的字符串模式。
+ `replacement`: 用于替换匹配匹配项的字符串。

## 示例（MongoDB 外壳）
<a name="replaceAll-examples"></a>

以下示例演示了如何在聚合管道中使用`$replaceAll`运算符将所有出现的字符串 “Chocolatier” 替换为 “Chocolatier Co.” 在 “产品” 系列的 “品牌名称” 字段中。

**创建示例文档**

```
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
  }
]);
```

**查询示例**

```
db.products.aggregate([
  {
    $addFields: {
      "brandName": {
        $replaceAll: {
          input: "$brandName",
          find: "Chocolatier",
          replacement: "Chocolate Co."
        }
      }
    }
  }
])
```

**输出**

```
[
  {
    _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
  }
]
```

## 代码示例
<a name="replaceAll-code"></a>

要查看使用该`$replaceAll`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

在 5.0 中引入

Amazon DocumentDB 中的运算符是聚合管道中使用的字符串表达式运算符，用于将字符串中第一次出现的指定子字符串替换为替换字符串。`$replaceOne`此运算符区分大小写，仅替换找到的第一个匹配项。

**参数**
+ `input`：要执行查找的字符串（字段）。
+ `find`: 要在输入中搜索的字符串。
+ `replacement`: 用于替换输入（字段）中首次出现的查找结果的字符串。

## 示例（MongoDB 外壳）
<a name="replaceOne-examples"></a>

以下示例演示了如何在聚合管道中使用`$replaceOne`运算符来替换产品名称中的子字符串。

**创建示例文档**

```
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 }
]);
```

**聚合示例**

```
db.products.aggregate([
  {
    $addFields: {
      standardizedName: {
        $replaceOne: {
          input: "$name",
          find: "Pack",
          replacement: "Package"
        }
      }
    }
  }
]);
```

**输出**

输出显示，每个产品名称中只有第一次出现的 “Pack” 被替换为 “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"
  }
```

## 代码示例
<a name="replaceOne-code"></a>

要查看使用该`$replaceOne`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$replaceRoot`运算符用于将根文档替换为指定的嵌入式文档。当您想要将嵌套文档提升到顶层或重构数据输出时，这很有用。

**参数**
+ `newRoot`：将替换现有根文档的新根文档。

## 示例（MongoDB 外壳）
<a name="replaceRoot-examples"></a>

此示例说明如何从买家订单中提取配送地址信息，这对于生成发货标签或地址列表非常有用。

**创建示例文档**

```
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 } ])
```

**查询示例**

```
db.orders.aggregate([
  {
    $replaceRoot: {
      newRoot: "$shippingAddress"
    }
  }
])
```

**输出**

```
{
    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'
  }
```

## 代码示例
<a name="replaceRoot-code"></a>

要查看使用该`$replaceRoot`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

8.0 版的新增内容

弹性集群不支持。

Amazon DocumentDB 中的`$replaceWith`聚合阶段用于将输入文档替换为新文档。输入文档上的所有现有字段（包括 \$1id 字段）都将替换为新文档。 `$replaceWith`通常用于扁平化文档或将嵌入式文档提升到顶层。

**参数**
+ `<replacement>`（必填）：将取代现有文档的新文档。

## 示例（MongoDB 外壳）
<a name="replaceWith-examples"></a>

以下示例演示如何使用`$replaceWith`运算符替换 Amazon DocumentDB 集合中的现有文档。

**创建示例文档**

```
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 ]
  }
]);
```

**查询示例**

```
db.restaurants.aggregate([
  { $replaceWith: {
      name: "$name",
      cuisine: "$cuisine",
      rating: { $avg: "$ratings" }
    }
  }
]);
```

**输出**

```
[
  {
    name: 'Biryani Adda',
    cuisine: 'Indian',
    rating: 3.4
  },
  {
    name: 'The Burger Spot',
    cuisine: 'American',
    rating: 2.7777777777777777
  }
]
```

## 代码示例
<a name="replaceWith-code"></a>

要查看使用该`$replaceWith`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$reverseArray`运算符用于按指定顺序反转数组中的元素。当您需要按相反方向对数组的元素进行重新排序时，此运算符很有用。

**参数**
+ `expression`: 要反转的数组表达式。

## 示例（MongoDB 外壳）
<a name="reverseArray-examples"></a>

以下示例演示如何使用`$reverseArray`运算符来反转数组中元素的顺序。

**创建示例文档**

```
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]}
]);
```

**查询示例**

```
db.miles.aggregate([
  {
    $project: {
      _id: 1,
      member_since: 1,
      credit_card: 1,
      reversed_flight_miles: { $reverseArray: "$flight_miles" }
    }
  }
]);
```

**输出**

```
{ "_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 ] }
```

在此示例中，`$reverseArray`运算符用于反转`flight_miles`数组的顺序。输出中的结果`reversed_flight_miles`字段按相反的顺序显示数组中的元素。

## 代码示例
<a name="reverseArray-code"></a>

要查看使用该`$reverseArray`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是在 Node.js 应用程序中使用`$reverseArray`运算符的示例：

```
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 ]

以下是在 Python 应用程序中使用`$reverseArray`运算符的示例：

```
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>

4.0 版的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的`$rtrim`运算符用于从字符串中删除尾随字符。默认情况下，它会删除尾随的空格字符，但您也可以通过传递 chars 参数来指定一组要删除的字符。

**参数**
+ `input`: 要从中删除尾随空格字符的输入字符串。
+ `chars`:（可选）删除特定字符。

## 示例（MongoDB 外壳）
<a name="rtrim-examples"></a>

以下示例演示如何使用`$rtrim`运算符从字符串中删除尾随的指定字符 (” \$1”)。

**创建示例文档**

```
db.collection.insert([
  { "name": "John Doe*  ", "age": 30 },
  { "name": "Jane Smith  ", "age": 25 },
  { "name": "Bob Johnson", "age": 35 }
]);
```

**查询示例**

```
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      name: { $rtrim: { input: "$name", chars: " *" } }, 
      age: 1
    }
  }
]);
```

**输出**

```
[
  { age: 30, name: 'John Doe' },
  { age: 25, name: 'Jane Smith' },
  { age: 35, name: 'Bob Johnson' }
]
```

## 代码示例
<a name="rtrim-code"></a>

要查看使用该`$rtrim`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$sample`聚合阶段用于从集合中随机选择指定数量的文档。这对于诸如数据分析、测试和生成样本以供进一步处理之类的任务非常有用。

**参数**
+ `size`：要随机选择的文档数量。

## 示例（MongoDB 外壳）
<a name="sample-examples"></a>

以下示例演示如何使用`$sample`舞台从`temp`集合中随机选择两个文档。

**创建示例文档**

```
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") }
]);
```

**查询示例**

```
db.temp.aggregate([
   { $sample: { size: 2 } }
])
```

**输出**

```
{ "_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") }
```

结果显示，10份文档中有2份是随机抽样的。现在，您可以使用这些文档来确定平均值或进行 min/max 计算。

## 代码示例
<a name="sample-code"></a>

要查看使用该`$sample`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

5.0 版的新增内容。

Amazon DocumentDB 中的`$search`运算符用于提供文本搜索功能。

**参数**

无

## 示例（MongoDB 外壳）
<a name="search-examples"></a>

以下示例演示如何使用`$search`运算符执行文本搜索查询。

**创建示例文档**

```
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." }
]);
```

**查询示例**

```
db.textcollection.find(
  { $text: { $search: "John" } }
);
```

**输出**

```
[
  {
    _id: 1,
    name: 'John Doe',
    description: 'This is a sample document about John Doe.'
  }
]
```

## 代码示例
<a name="search-code"></a>

要查看使用该`$search`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$second`运算符从日期或时间戳中提取秒部分。它用于从日期或时间戳字段中检索秒值。

**参数**
+ `expression`：要从中提取秒值的日期或时间戳字段。此表达式可以是字段路径，也可以是任何解析为日期或时间戳的有效表达式。

## 示例（MongoDB 外壳）
<a name="second-examples"></a>

以下示例演示如何使用`$second`运算符从日期字段中提取秒分量。

**创建示例文档**

```
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") }
]);
```

**查询示例**

```
db.users.aggregate([{ $project: { name: 1, dobSeconds: { $second: "$dob" } } }])
```

**输出**

```
[
  { "_id" : ObjectId("6089a9c306a829d1f8b456a1"), "name" : "John", "dobSeconds" : 45 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a2"), "name" : "Jane", "dobSeconds" : 59 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a3"), "name" : "Bob", "dobSeconds" : 0 }
]
```

## 代码示例
<a name="second-code"></a>

要查看使用该`$second`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

8.0 版的新增内容

弹性集群不支持。

Amazon DocumentDB 中的`$set`聚合阶段允许您在聚合管道期间添加新字段或更新文档中的现有字段值。

**参数**
+ `expression`：要计算的表达式。这可以是任何有效的聚合表达式，包括字段引用和算术运算。

## 示例（MongoDB 外壳）
<a name="set-stage-examples"></a>

以下示例演示了如何使用`$set`聚合阶段通过将字段乘以`quantity`字段来计算总数。`price`

**创建示例文档**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**聚合示例**

```
db.inventory.aggregate([
  {
    $set: {
      total: { $multiply: ["$quantity", "$price"] }
    }
  }
])
```

**输出**

```
[
  {
    _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
  }
]
```

## 代码示例
<a name="set-stage-code"></a>

要查看使用该`$set`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

Amazon DocumentDB 中的`$setDifference`运算符用于比较两个集合，并返回第一个集合中但不在第二个集合中的元素。此运算符对于查找两个集合之间的唯一元素很有用。

**参数**
+ `firstSet`：要比较的第一组。
+ `secondSet`：要比较的第二组。

## 示例（MongoDB 外壳）
<a name="setDifference-examples"></a>

以下示例演示如何使用`$setDifference`运算符来查找两个集合之间的唯一元素。

**创建示例文档**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry", "date"] },
  { _id: 2, fruits: ["banana", "cherry", "date", "elderberry"] }
]);
```

**查询示例**

```
db.collection.aggregate([
  {
    $project: {
      uniqueFruits: { $setDifference: ["$fruits", ["banana", "cherry", "date"]] }
    }
  }
]);
```

**输出**

```
[
  { "_id": 1, "uniqueFruits": ["apple"] },
  { "_id": 2, "uniqueFruits": ["elderberry"] }
]
```

该查询执行以下步骤：

1. 它使用`$project`舞台`uniqueFruits`为每个文档创建一个新字段。

2. `$setDifference`运算符将`fruits`数组与数组进行比较，`[&quot;banana&quot;, &quot;cherry&quot;, &quot;date&quot;]`并返回`fruits`数组中唯一的元素。

## 代码示例
<a name="setDifference-code"></a>

要查看使用该`$setDifference`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是如何在 Node.js 应用程序中使用`$setDifference`运算符的示例：

```
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 ]

以下是如何在 Python 应用程序中使用`$setDifference`运算符的示例：

```
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>

Amazon DocumentDB 中的`$setEquals`运算符用于确定两组是否相等。它比较两个数组，并返回它们`true`是否包含相同的不同元素，无论它们的顺序如何。

**参数**
+ `expression1`: 第一个要比较的数组。
+ `expression2`: 第二个要比较的数组。

## 示例（MongoDB 外壳）
<a name="setEquals-examples"></a>

以下示例演示如何使用运`$setEquals`算符比较两组值。

**创建示例文档**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry"] },
  { _id: 2, fruits: ["banana", "apple", "cherry"] },
  { _id: 3, fruits: ["apple", "banana", "orange"] }
])
```

**查询示例**

```
db.collection.find({
  $expr: {
    $setEquals: ["$fruits", ["apple", "banana", "cherry"]]
  }
})
```

**输出**

```
{ "_id" : 1, "fruits" : [ "apple", "banana", "cherry" ] }
{ "_id" : 2, "fruits" : [ "banana", "apple", "cherry" ] }
```

该查询使用`$setEquals`运算符将每个文档的`fruits`字段与数组进行比较`[&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]`。返回该`fruits`字段等于比较数组的文档。

## 代码示例
<a name="setEquals-code"></a>

要查看使用该`$setEquals`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$setIntersection`运算符用于返回两个或多个数组之间的公共元素。此运算符在处理数据集时特别有用，它允许您找到多个数据集的交集。

**参数**
+ `array1`: 第一个相交的数组。
+ `array2`: 第二个要相交的数组。
+ `arrayN`:（可选）要相交的其他数组。

## 示例（MongoDB 外壳）
<a name="setIntersection-examples"></a>

以下示例演示如何使用`$setIntersection`运算符来查找两个数组之间的公共元素。

**创建示例文档**

```
db.collection.insertMany([
  { _id: 1, colors: ["red", "blue", "green"] },
  { _id: 2, colors: ["blue", "yellow", "orange"] },
  { _id: 3, colors: ["red", "green", "purple"] }
])
```

**查询示例**

```
db.collection.aggregate([
  { $project: {
      _id: 1,
      commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
    }
  }
])
```

**输出**

```
[
  { "_id": 1, "commonColors": ["red", "blue", "green"] },
  { "_id": 2, "commonColors": ["blue"] },
  { "_id": 3, "commonColors": ["red", "green"] }
]
```

## 代码示例
<a name="setIntersection-code"></a>

要查看使用该`$setIntersection`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$setIsSubset`运算符用于确定一组值是否为另一组值的子集。它对于对数组字段执行基于集合的比较和操作很有用。

**参数**
+ `field`: 要应用`$setIsSubset`运算符的字段。
+ `set`：用于比较字段的集合。

## 示例（MongoDB 外壳）
<a name="setIsSubset-examples"></a>

以下示例演示如何使用`$setIsSubset`运算符来检查`tags`字段是否为指定集合的子集。

**创建示例文档**

```
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"] }
]);
```

**查询示例**

```
db.products.find({
  $expr: { $setIsSubset: [["tag1", "tag2"], "$tags"] }
})
```

\$1注意：\$1 `$setIsSubset` 是一个聚合运算符，不能直接用于 find () 查询。在此示例中，`$expr`与一起使用`find()`来弥合查询运算符和聚合表达式之间的差距。

**输出**

```
[
  { "_id" : 1, "name" : "Product A", "tags" : [ "tag1", "tag2", "tag3" ] },
  { "_id" : 2, "name" : "Product B", "tags" : [ "tag1", "tag2" ] }
]
```

该查询返回该`tags`字段是集合子集的子集的文档`[&quot;tag1&quot;, &quot;tag2&quot;]`。

## 代码示例
<a name="setIsSubset-code"></a>

要查看使用该`$setIsSubset`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$setUnion`聚合运算符用于组合两组或多组值，并返回一个包含输入集中所有唯一元素的集合。当您需要对文档中的数组字段执行基于集合的操作时，此运算符很有用。

**参数**
+ `expression1`: 解析为数组的表达式。
+ `expression2`: 解析为数组的表达式。
+ `expressionN`：解析为数组的其他表达式（可选）。

## 示例（MongoDB 外壳）
<a name="setUnion-examples"></a>

以下示例演示如何使用`$setUnion`运算符将集合中两个数组字段中的唯一元素组合在一起。

**创建示例文档**

```
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"] }
]);
```

**查询示例**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      allInterests: { $setUnion: ["$hobbies", "$skills"] }
    }
  }
]);
```

**输出**

```
[
  { "_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" ] }
]
```

在此示例中，`$setUnion`运算符用于组合每个用户文档的`hobbies`和`skills`数组字段中的唯一元素。生成的`allInterests`字段包含每个用户的所有独特爱好和技能的组合。

## 代码示例
<a name="setUnion-code"></a>

要查看使用该`$setUnion`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

在 Amazon DocumentDB 中，`$skip`运算符用于偏移查询结果的起点，允许您检索匹配文档的特定子集。这在分页场景中特别有用，在这种场景中，您要检索结果的后续页面。

**参数**
+ `skip`：返回剩余文档之前要跳过的文档数。

## 示例（MongoDB 外壳）
<a name="skip-examples"></a>

以下示例演示如何使用`$skip`运算符从集合中检索第二页结果（文档 11-20）。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.collection.find({}, { "name": 1 })
             .skip(10)
             .limit(10);
```

**输出**

```
[
  { "_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" }
]
```

## 代码示例
<a name="skip-code"></a>

要查看使用该`$skip`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$slice`聚合运算符使您可以通过从数组的开头或结尾遍历数组来返回数组的子集。这用于显示数组字段中有限数量的项目，例如顶部或底部 N 个项目。

**参数**
+ `array`: 要切片的数组字段。
+ `n`：一个整数，它指定要返回的元素数。正值从数组的开头开始，而负值从数组的末尾开始。

## 示例（MongoDB 外壳）
<a name="slice-examples"></a>

以下示例演示如何使用`$slice`返回每位厨师最喜欢的前两个糖果。

**创建示例文档**

```
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" ] }
]);
```

**查询示例**

```
db.sweets.aggregate([
  { $project: { _id: 0, name: 1, topTwoFavorites: { $slice: [ "$favorites", 2 ] } } }
]);
```

**输出**

```
[
  { name: 'Alvin', topTwoFavorites: [ 'chocolate', 'cake' ] },
  { name: 'Tom', topTwoFavorites: [ 'donuts', 'pudding' ] },
  { name: 'Jessica', topTwoFavorites: [ 'fudge', 'smores' ] },
  { name: 'Rachel', topTwoFavorites: [ 'ice cream' ] }
]
```

在此示例中，`$slice`运算符用于从每个文档的`favorites`数组中提取前两个元素。

## 代码示例
<a name="slice-code"></a>

要查看使用该`$slice`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$size`运算符用于返回数组字段中的项目数。这可以用来确定存储在文档中的数组中的元素数量。

**参数**
+ `field`: 要返回其数组大小的字段路径。

## 示例（MongoDB 外壳）
<a name="size-examples"></a>

此示例说明如何使用`$size`运算符返回每个用户关注的团队数量。

**创建示例文档**

```
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"] }
]);
```

**查询示例**

```
db.profiles.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      "numberOfTeams": { $size: "$teams" }
    }
  }
])
```

**输出**

```
[
  { name: 'John Doe', numberOfTeams: 3 },
  { name: 'Jane Smith', numberOfTeams: 2 },
  { name: 'Bob Johnson', numberOfTeams: 3 }
]
```

## 代码示例
<a name="size-code"></a>

要查看使用该`$size`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$sort`聚合阶段根据指定的字段值对管道中的文档进行排序。根据提供的排序标准，文档按升序或降序排列。

**参数**
+ `field`：要作为排序依据的字段名称。
+ `order`：`1`用于升序或`-1`降序。

## 示例（MongoDB 外壳）
<a name="sort-examples"></a>

以下示例演示了使用`$sort`舞台按价格降序对产品进行排序。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.products.aggregate([
  { $sort: { price: -1 } }
]);
```

**输出**

```
[
  { _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 }
]
```

## 代码示例
<a name="sort-code"></a>

要查看使用`$sort`聚合阶段的代码示例，请选择要使用的语言对应的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$split`聚合运算符用于根据指定的分隔符将字符串拆分为子字符串数组。这对于解析复杂的字符串字段和提取单个组件进行进一步处理非常有用。

**参数**
+ `string`: 要拆分的字符串。
+ `delimiter`：用于拆分输入字符串的字符或字符串。

## 示例（MongoDB 外壳）
<a name="split-examples"></a>

在这个例子中，我们使用`$split`将 “Desk” 字段的组件分成一个数组，这样可以更轻松地处理数据。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.people.aggregate([
  { $project: { parts: { $split: ["$Desk", "-"] } } }
]);
```

**输出**

```
{ "_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" ] }
```

的输出`$split`创建了一个数组，可以在应用程序中使用该数组来显示员工的信息。

## 代码示例
<a name="split-code"></a>

要查看使用该`$split`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

Amazon DocumentDB 中的`$sqrt`运算符用于计算数字的平方根。

**参数**
+ `expression`: 参数可以是任何有效的表达式，只要它解析为非负数即可。

## 示例（MongoDB 外壳）
<a name="sqrt-examples"></a>

以下示例演示如何使用运`$sqrt`算符来计算数字的平方根。

**创建示例文档**

```
db.numbers.insertMany([
  { "_id": 1, "number": 16 },
  { "_id": 2, "number": 36 },
  { "_id": 3, "number": 64 }
]);
```

**查询示例**

```
db.numbers.aggregate([
  { $project: {
    "_id": 1,
    "square_root": { $sqrt: "$number" }
  }}
]);
```

**输出**

```
[
  { _id: 1, square_root: 4 },
  { _id: 2, square_root: 6 },
  { _id: 3, square_root: 8 }
]
```

## 代码示例
<a name="sqrt-code"></a>

要查看使用该`$sqrt`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$strLenBytes`运算符用于确定字符串的长度（以字节为单位）。当您需要了解字符串字段的存储大小时，这很有用，尤其是在处理每个字符可能使用超过一个字节的 Unicode 字符时。

**参数**
+ `expression`：要计算长度的字符串表达式。

## 示例（MongoDB 外壳）
<a name="strLenBytes-examples"></a>

此示例演示如何使用`$strLenBytes`运算符计算字符串字段的长度（以字节为单位）。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenBytes: "$Desk" }
    }
  }
])
```

**输出**

```
{ "_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 }
```

请注意，“Düseldorf-bvv-021” 字符串的长度为 19 字节，这与码点数 (18) 不同，因为 Unicode 字符 “U” 占用 2 个字节。

## 代码示例
<a name="strLenBytes-code"></a>

要查看使用该`$strLenBytes`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$strLenCP`运算符用于确定以代码点为单位的字符串表达式的长度（Unicode 字符）。当你需要知道字符串中的字符数而不是字节数时，这很有用。

**参数**
+ `expression`：要返回长度的字符串表达式（以代码点为单位）。

## 示例（MongoDB 外壳）
<a name="strLenCP-examples"></a>

以下示例演示如何使用`$strLenCP`运算符来确定包含 Unicode 字符的字符串的长度。

**创建示例文档**

```
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" }
])
```

**查询示例**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenCP: "$Desk" }
    }
  }
])
```

**输出**

```
{ "_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 }
```

请注意包含 Unicode 字符 (U) 的 “杜塞尔多夫-bvv-021” 字符串的长度测量值的差异。`$strLenCP`运算符正确计算 Unicode 字符数，而`$strLenBytes`运算符则计算字节数。

## 代码示例
<a name="strLenCP-code"></a>

要查看使用该`$strLenCP`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是在带有 MongoDB 驱动程序的 Node.js 应用程序中使用该`$strLenCP`运算符的示例：

```
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 ]

以下是在带 PyMongo 驱动程序的 Python 应用程序中使用`$strLenCP`运算符的示例：

```
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>

Amazon DocumentDB 中的`$strcasecmp`运算符在两个字符串之间执行不区分大小写的比较。它返回一个整数值，表示两个输入字符串的字典比较，忽略大小写差异。

**参数**
+ `string1`: 要比较的第一个字符串。
+ `string2`: 要比较的第二个字符串。

## 示例（MongoDB 外壳）
<a name="strcasecmp-examples"></a>

此示例演示如何使用`$strcasecmp`运算符比较`people`集合中的办公桌位置字符串，同时忽略大小写差异。

**创建示例文档**

```
db.people.insertMany([
  { "_id": 1, "Desk": "mke233-wi" },
  { "_id": 2, "Desk": "MKE233-WI" },
  { "_id": 3, "Desk": "mke233-wi" }
]);
```

**查询示例**

```
db.people.aggregate([
  {
    $project: {
      item: 1,
      compare: { $strcasecmp: ["$Desk", "mke233-wi"] }
    }
  }
]);
```

**输出**

```
{ "_id" : 1, "compare" : 0 }
{ "_id" : 2, "compare" : 0 }
{ "_id" : 3, "compare" : 0 }
```

输出显示，`&quot;Desk&quot;`字段和字符串之间的比较会`&quot;mke233-wi&quot;`返回`0`所有三个文档，这表明忽略大小写时，字符串相等。

## 代码示例
<a name="strcasecmp-code"></a>

要查看使用该`$strcasecmp`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$substr`运算符用于从给定字符串中提取子字符串。当您需要根据字符范围而不是字节范围定义子字符串时，它特别有用。在处理 Unicode 字符串时，这一点尤其重要，因为在这些字符串中，用于表示字符的字节数可能会有所不同。

**参数**
+ `string`：要从中提取子字符串的输入字符串。
+ `start`：要提取的子字符串的起始位置（从零开始）。可以是非负整数表达式。
+ `length`：提取的子字符串中的字符数。可以是非负整数表达式。

## 示例（MongoDB 外壳）
<a name="substr-examples"></a>

在此示例中，我们将演示如何使用从员工办公桌位置提取州缩写。`$substr`

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substr: ["$Desk", 12, 3] }
    }
  }
])
```

**输出**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

## 代码示例
<a name="substr-code"></a>

要查看使用该`$substr`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$substrBytes`运算符用于根据指定的字节范围从字符串中提取子字符串。当您需要从字符串中提取子字符串并且表示字符串中每个字符所需的字节数很重要时，此运算符很有用。

与之不同`$substrCP`，它对Unicode码点的数量进行`$substrBytes`运算，对表示字符串中字符所需的字节数进行运算。这在处理包含非 ASCII 字符的字符串时特别有用，因为这些字符可能需要多个字节才能表示。

\$1注意：\$1 自 3.4 版起`$substr`已被弃用。 `$substr`现在是的别名`$substrBytes`。

**参数**
+ `string`：要从中提取子字符串的输入字符串。
+ `startByte`：要提取的子字符串的起始字节位置（从零开始）。负值可用于指定从字符串末尾开始的位置。
+ `length`：要提取的子字符串中的字节数。

## 示例（MongoDB 外壳）
<a name="substrBytes-examples"></a>

在此示例中，我们将使用`$substrBytes`从包含非 ASCII 字符的字符串中提取子字符串。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrBytes: [ "$Desk", 12, 3] }
    }
  }
])
```

**输出**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

在此示例中，我们使用从字段`$substrBytes`的第 12 个字节开始提取一个 3 字节的`Desk`子字符串。这允许我们提取 2 个字符的状态缩写，即使该字符串可能包含非 ASCII 字符。

## 代码示例
<a name="substrBytes-code"></a>

要查看使用该`$substrBytes`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$substrCP`运算符用于从字符串中提取子字符串，其中子字符串指定为 UTF-8 码点范围 (CP)。此运算符在处理 Unicode 字符串时特别有用，因为它允许您提取子字符串，而不必担心字符的底层字节表示形式。

与对字节位置进行`$substrBytes`操作的运算符不同，该`$substrCP`运算符使用码点位置。这使得处理包含非 ASCII 字符的字符串变得更加容易，因为代码点的数量可能与字节数或字符数不匹配。

**参数**
+ `string`：要从中提取子字符串的输入字符串。
+ `start`：从中提取子字符串的起始码点位置（从零开始）。
+ `length`：要提取的代码点数。

## 示例（MongoDB 外壳）
<a name="substrCP-examples"></a>

在此示例中，我们将使用`$substrCP`运算符从包含员工办公桌位置的字符串中提取州缩写。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrCP: ["$Desk", 25, 2] }
    }
  }
]);
```

**输出**

```
{ "_id" : 1, "state" : "MN" }
{ "_id" : 2, "state" : "LA" }
{ "_id" : 3, "state" : "CA" }
```

在此示例中，我们知道州缩写从`Desk`字段的第 25 个代码点开始，长度为 2 个代码点。通过使用`$substrCP`运算符，我们可以提取状态缩写，而不必担心字符串的底层字节表示形式。

## 代码示例
<a name="substrCP-code"></a>

要查看使用该`$substrCP`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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()
```

在 Node.js 和 Python 示例中，我们都使用`$substrCP`运算符从`Desk`字段中提取状态缩写，类似于 MongoDB 命令行管理程序示例。

------

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

Amazon DocumentDB 中的`$subtract`运算符用于减去值。它可以用来减去日期、数字或两者的组合。此运算符可用于计算两个日期之间的差值或从数字中减去一个值。

**参数**
+ `expression1`：要减去的第一个值。
+ `expression2`：要从`<expression1>`中减去的第二个值。

## 示例（MongoDB 外壳）
<a name="subtract-examples"></a>

以下示例演示如何使用`$subtract`运算符来计算两个日期之间的差。

**创建示例文档**

```
db.dates.insert([
  {
  "_id": 1,
  "startDate": ISODate("2023-01-01T00:00:00Z"),
  "endDate": ISODate("2023-01-05T12:00:00Z")
  }
]);
```

**查询示例**

```
db.dates.aggregate([
  {
    $project: {
      _id: 1,
      durationDays: {
        $divide: [
          { $subtract: ["$endDate", "$startDate"] },
          1000 * 60 * 60 * 24  // milliseconds in a day
        ]
      }
    }
  }
]);
```

**输出**

```
[ { _id: 1, durationDays: 4.5 } ]
```

在此示例中，`$subtract`运算符用于计算`$endDate`和之间的差值（`$startDate`以天为单位）。

## 代码示例
<a name="subtract-code"></a>

要查看使用该`$subtract`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$sum`运算符返回一组中每个文档的指定表达式的总和。它是一个组累加器运算符，通常用于聚合管道的 \$1group 阶段来执行求和计算。

**参数**
+ `expression`：要求和的数值表达式。这可以是字段路径、表达式或常量。

## 示例（MongoDB 外壳）
<a name="sum-examples"></a>

以下示例演示如何使用运`$sum`算符来计算每种产品的总销售额。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.sales.aggregate([
  { $group: {
      _id: "$product",
      totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } }
    }}
]);
```

**输出**

```
[
  { "_id": "abc", "totalSales": 50 },
  { "_id": "xyz", "totalSales": 120 }
]
```

## 代码示例
<a name="sum-code"></a>

要查看使用该`$sum`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

弹性集群不支持。

`$switch`运算符是 Amazon DocumentDB 中的条件表达式运算符，它允许您评估案例表达式列表并返回计算结果为 true 的第一个案例的值，如果没有大小写表达式为真，则返回默认值。

**参数**
+ `branches`：一个文档数组，每个文档都有一个包含要计算的布尔表达式的 case 字段，以及一个包含在 case 表达式为真时要返回的值的 then 字段。
+ `default`:（可选）如果没有一个 case 表达式为真时要返回的值。

## 示例（MongoDB 外壳）
<a name="switch-examples"></a>

以下示例演示如何使用`$switch`运算符根据订单总额确定订单的运费。

**创建示例文档**

```
db.orders.insertMany([
  { _id: 1, total: 50 },
  { _id: 2, total: 150 },
  { _id: 3, total: 250 }
]);
```

**查询示例**

```
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
        }
      }
    }
  }
])
```

**输出**

```
[
  {
    "_id": 1,
    "total": 50,
    "shippingCost": 5
  },
  {
    "_id": 2,
    "total": 150,
    "shippingCost": 10
  },
  {
    "_id": 3,
    "total": 250,
    "shippingCost": 15
  }
]
```

## 代码示例
<a name="switch-code"></a>

要查看使用该`$switch`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$toBool`运算符将表达式转换为布尔值。

**参数**
+ `expression`：要转换为布尔值的表达式。

**注意**：任何字符串都将转换为`true`。

## 示例（MongoDB 外壳）
<a name="toBool-examples"></a>

以下示例演示如何使用`$toBool`运算符对来自不同数据类型的设备状态值进行标准化。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.deviceStates.aggregate([
  {
    $project: {
      _id: 1,
      deviceId: 1,
      isActive: { $toBool: "$status" }
    }
  }
]);
```

**输出**

```
[
  { "_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 }
]
```

## 代码示例
<a name="toBool-code"></a>

要查看使用该`$toBool`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$toDate`聚合运算符用于将日期或日期和时间字符串转换为 BSON 日期类型。这是运算符的反向`$dateToString`运算。

**参数**
+ `dateString`：要转换为 BSON 日期类型的日期或日期和时间的字符串表示形式。
+ `format`:（可选）指定格式的字符串`dateString`。如果未提供，则操作员将尝试`dateString`以各种标准日期和时间格式解析。
+ `timezone`:（可选）一个字符串，表示用于转换的时区。如果未提供，则使用当地时区。

## 示例（MongoDB 外壳）
<a name="toDate-examples"></a>

以下示例演示如何使用`$toDate`运算符将日期字符串转换为 BSON 日期类型。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.events.aggregate([
  {
    $project: {
      eventName: 1,
      eventTimeDate: { $toDate: "$eventTime" }
    }
  }
]);
```

**输出**

```
[
  {
    "_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")
  }
]
```

## 代码示例
<a name="toDate-code"></a>

要查看使用该`$toDate`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$toDecimal`运算符用于将值转换为 Decimal128 数据类型。当您需要执行精确的十进制算术或处理无法使用 Double 数据类型精确表示的大十进制值时，这很有用。

**参数**
+ `expression`：要转换为 Decimal128 数据类型的表达式。

## 示例（MongoDB 外壳）
<a name="toDecimal-examples"></a>

此示例演示如何使用`$toDecimal`运算符将字符串值转换为 Decimal128 数据类型。

**创建示例文档**

```
db.numbers.insertOne({ _id: 1, value: "3.14" });
db.numbers.insertOne({ _id: 2, value: "2.71" });
```

**查询示例**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    decimalValue: { $toDecimal: "$value" }
  }}
])
```

**输出**

```
[
  { "_id" : 1, "decimalValue" : Decimal128("3.14") },
  { "_id" : 2, "decimalValue" : Decimal128("2.71") }
]
```

## 代码示例
<a name="toDecimal-code"></a>

要查看使用该`$toDecimal`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$toDouble`运算符用于将值转换为双精度 64 位浮点数。当您需要对最初不是数字格式的值执行算术运算时，这可能很有用。

**参数**

`&lt;expression&gt;`：要转换为双精度值的表达式。这可以是任何解析为数字、字符串或布尔值的有效表达式。

## 示例（MongoDB 外壳）
<a name="toDouble-examples"></a>

此示例演示如何使用`$toDouble`运算符将字符串值转换为数值以进行数学计算。

**创建示例文档**

```
db.numbers.insertMany([
  { _id: 1, value: "10.5" },
  { _id: 2, value: "20.25" },
  { _id: 3, value: "7" }
])
```

**查询示例**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      value: 1,
      double_value: { $toDouble: "$value" },
      double_plus_five: { $add: [{ $toDouble: "$value" }, 5] }
    }
  }
])
```

**输出**

```
[
  { "_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 }
]
```

## 代码示例
<a name="toDouble-code"></a>

要查看使用该`$toDouble`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$toInt`运算符用于将输入值转换为整数数据类型。当您需要确保将字段或表达式表示为整数时，此运算符很有用，这对于某些操作或数据处理任务可能很重要。

**参数**
+ `expression`：要转换为整数的表达式。

## 示例（MongoDB 外壳）
<a name="toInt-examples"></a>

以下示例演示如何使用`$toInt`运算符将字符串值转换为整数。

**创建示例文档**

```
db.numbers.insertMany([
  { "name": "one", "value": "1" },
  { "name": "hundred", "value": "100" }
]);
```

**查询示例**

```
db.numbers.aggregate([
  { $project: {
    "_id": 0,
    "name": 1,
    "intValue": { $toInt: "$value" }
  }}
]);
```

**输出**

```
{ "name": "one", "intValue": 1 }
{ "name": "hundred", "intValue": 100 }
```

## 代码示例
<a name="toInt-code"></a>

要查看使用该`$toInt`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$toLong`运算符用于将值转换为 64 位整数（长）数据类型。当您需要对可能存储为字符串或其他数据类型的数值执行算术运算或比较时，这可能很有用。

**参数**
+ `expression`：要转换为 64 位整数的表达式。

## 示例（MongoDB 外壳）
<a name="toLong-examples"></a>

此示例演示如何使用`$toLong`运算符将字符串值转换为 64 位整数。

**创建示例文档**

```
db.numbers.insertMany([
  { _id: 1, value: "42" },
  { _id: 3, value: "9223372036854775807" }
]);
```

**查询示例**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      longValue: { $toLong: "$value" }
    }
  }
])
```

**输出**

```
[
  { "_id" : 1, "longValue" : 42 },
  { "_id" : 3, "longValue" : 9223372036854775807 }
]
```

## 代码示例
<a name="toLong-code"></a>

要查看使用该`$toLong`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$toLower`运算符用于将字符串转换为小写。

**参数**
+ `expression`: 要转换为小写的字符串表达式。

## 示例（MongoDB 外壳）
<a name="toLower-examples"></a>

以下示例演示如何使用`$toLower`运算符将`Desk`字段转换为小写。

**创建示例文档**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" }
]);
```

**查询示例**

```
db.locations.aggregate([
  { $project: { item: { $toLower: "$Desk" } } }
]);
```

**输出**

```
{ "_id" : 1, "item" : "düsseldorf-bvv-021" }
{ "_id" : 2, "item" : "munich-hgg-32a" }
```

## 代码示例
<a name="toLower-code"></a>

要查看使用该`$toLower`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$toObjectId`运算符用于将的字符串表示形式转换为实际 ObjectId 的数据类型。 ObjectId 这在处理以字符串表示形式存储的数据时非常有用 ObjectIds，因为它允许您执行需要该 ObjectId 数据类型的操作。

**参数**
+ `expression`: 表示有效值的字符串表达式 ObjectId。

## 示例（MongoDB 外壳）
<a name="toObjectId-examples"></a>

以下示例演示如何使用`$toObjectId`运算符将的字符串表示形式转换为 ObjectId 数据类型。 ObjectId 

**创建示例文档**

```
db.employees.insertMany([
  { _id: 1, empId:"64e5f8886218c620cf0e8f8a", name: "Carol Smith", employeeId: "c720a" },
  { _id: 2, empId:"64e5f94e6218c620cf0e8f8c", name: "Bill Taylor", employeeId: "c721a" }
]);
```

**查询示例**

```
db.employees.aggregate([
  { $project: {
    "empIdAsObjectId": {$toObjectId: "$empId"}}
  }
]);
```

**输出**

```
[
  { _id: 1, empIdAsObjectId: ObjectId('64e5f8886218c620cf0e8f8a') },
  { _id: 2, empIdAsObjectId: ObjectId('64e5f94e6218c620cf0e8f8c') }
]
```

## 代码示例
<a name="toObjectId-code"></a>

要查看使用该`$toObjectId`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$toString`运算符用于将任何类型的值（空值除外）转换为字符串表示形式。当您需要对最初不是字符串格式的值执行字符串操作时，这可能很有用。

**参数**
+ `expression`: 要转换为字符串的表达式。

## 示例（MongoDB 外壳）
<a name="toString-examples"></a>

以下示例演示如何使用`$toString`运算符将数值转换为字符串。

**创建示例文档**

```
db.numbers.insertMany([
  { "_id": 1, "value": 42 },
  { "_id": 2, "value": 3.14 }
]);
```

**查询示例**

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

**输出**

```
{ "_id": 1, "valueAsString": "42" }
{ "_id": 2, "valueAsString": "3.14" }
```

## 代码示例
<a name="toString-code"></a>

要查看使用该`$toString`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$toUpper`运算符用于将字符串转换为大写。

**参数**
+ `expression`: 要转换为大写的字符串表达式。

## 示例（MongoDB 外壳）
<a name="toUpper-examples"></a>

以下示例演示如何使用运`$toUpper`算符将`Desk`字段转换为大写。

**创建示例文档**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "düsseldorf-bvv-021" },
  { "_id": 2, "Desk": "munich-hgg-32a" }
]);
```

**查询示例**

```
db.locations.aggregate([
  { $project: { item: { $toUpper: "$Desk" } } }
]);
```

**输出**

```
{ "_id" : 1, "item" : "DüSSELDORF-BVV-021" }
{ "_id" : 2, "item" : "MUNICH-HGG-32A" }
```

## 代码示例
<a name="toUpper-code"></a>

要查看使用该`$toUpper`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容

Amazon DocumentDB 中的`$trim`运算符用于从字符串中删除前导 and/or 尾随的空格字符。

**参数**
+ `input`: 要修剪的字符串表达式。
+ `chars`:（可选）指定要从输入的开头和结尾修剪的字符，默认为空格。

## 示例（MongoDB 外壳）
<a name="trim-examples"></a>

以下示例演示如何使用`$trim`运算符从字符串中删除前导和尾随空格。

**创建示例文档**

```
db.people.insertMany([
  { "name": "   John Doe   " },
  { "name": "   Bob Johnson   " }
])
```

**查询示例**

```
db.people.aggregate([
  { $project: {
    "name": { $trim: {input: "$name"}}
  }}
])
```

**输出**

```
[
  { "name": "John Doe" },
  { "name": "Bob Johnson" }
]
```

## 代码示例
<a name="trim-code"></a>

要查看使用该`$trim`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$type`聚合运算符返回指定字段的 BSON 数据类型。这对于在聚合操作期间识别字段值的数据类型非常有用。

**参数**
+ `expression`：要返回其类型的字段或表达式。

## 示例（MongoDB 外壳）
<a name="type-aggregation-examples"></a>

以下示例演示如何使用`$type`运算符来识别每种产品的价格字段的数据类型。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      price: 1,
      priceType: { $type: "$price" }
    }
  }
]);
```

**输出**

```
[
  { _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' }
]
```

## 代码示例
<a name="type-aggregation-code"></a>

要查看使用`$type`聚合运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

8.0 版的新增内容

弹性集群不支持。

Amazon DocumentDB 中的`$unset`聚合阶段允许您从文档中删除字段。

**参数**
+ `expression`：字段名称或多个字段名称的列表。

## 示例（MongoDB 外壳）
<a name="unset-stage-examples"></a>

以下示例演示了如何使用`$unset`聚合阶段来移除字`price`段。

**创建示例文档**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**聚合示例**

```
db.inventory.aggregate([
  {
    $unset: "price"
  }
])
```

**输出**

```
[
  {
    _id: ObjectId('69248951d66dcae121d2950d'),
    item: 'pencil',
    quantity: 100
  },
  {
    _id: ObjectId('69248951d66dcae121d2950e'),
    item: 'pen',
    quantity: 204
  }
]
```

## 代码示例
<a name="unset-stage-code"></a>

要查看使用该`$unset`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$unwind`运算符用于从输入文档中解构一个数组字段，为每个元素输出一个文档。当您要对数组的各个元素执行操作（例如筛选、排序或转换数据）时，这可能很有用。

**参数**
+ `path`: 要展开的数组字段的路径。
+ `includeArrayIndex`:（可选）指定用于保存数组元素索引的新字段的名称。
+ `preserveNullAndEmptyArrays`:（可选）确定当数组字段为空还是空数组时，操作是保留原始文档。

## 示例（MongoDB 外壳）
<a name="unwind-examples"></a>

以下示例演示如何使用`$unwind`运算符解构数组字段并对各个元素执行进一步的操作。

**创建示例文档**

```
db.people.insertMany([
  { _id: 1, name: "jon", hobbies: ["painting", "dancing", "singing"] },
  { _id: 2, name: "jane", hobbies: ["reading", "swimming"] },
  { _id: 3, name: "jack", hobbies: [] }
])
```

**查询示例**

```
db.people.aggregate([
  { $unwind: "$hobbies" }
])
```

**输出**

```
[
  { _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' }
]
```

## 代码示例
<a name="unwind-code"></a>

要查看使用该`$unwind`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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()
```

------

# \$1向量搜索
<a name="vectorSearch"></a>

8.0 版的新增内容

弹性集群不支持。

Amazon DocumentDB 中的`$vectorSearch`运算符允许您执行矢量搜索，这是机器学习中使用的一种方法，通过使用距离或相似度指标比较它们的矢量表示来查找相似的数据点。该功能将基于 JSON 的文档数据库的灵活性和丰富的查询功能与矢量搜索的强大功能相结合，使您能够构建机器学习和生成式 AI 用例，例如语义搜索、产品推荐等。

**参数**
+ `<exact>`（可选）：指定是运行精确最近邻 (ENN) 还是近似最近邻 (ANN) 搜索的标志。值可以是以下值之一：
+ false-运行 ANN 搜索
+ true-运行 ENN 搜索

如果省略或设置为 false，`numCandidates`则为必填项。

```
- `<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.
```

## 示例（MongoDB 外壳）
<a name="vectorSearch-examples"></a>

以下示例演示如何使用`$vectorSearch`运算符根据其向量表示法查找相似的产品描述。

**创建示例文档**

```
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]
  }
]);
```

**创建矢量搜索索引**

```
db.runCommand(
    {
        createIndexes: "products",
        indexes: [{
            key: {
                "description_vector": "vector"
            },
            vectorOptions: {
                type: "hnsw",
                dimensions: 3,
                similarity: "cosine",
                m: 16,
                efConstruction: 64
            },
            name: "description_index"
        }]
    }
);
```

**查询示例**

```
db.products.aggregate([
  { $vectorSearch: {
      index: "description_index",
      limit: 2,
      numCandidates: 10,
      path: "description_vector",
      queryVector: [0.1, 0.2, 0.3]
    }
  }
]);
```

**输出**

```
[
  {
    "_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 ]
  }
]
```

## 代码示例
<a name="vectorSearch-code"></a>

要查看使用该`$vectorSearch`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$week`运算符根据 ISO 8601 标准返回日期的周数 (0-53)。周数是根据年份和星期几计算的，星期一是一周的第一天。

**参数**

无

## 示例（MongoDB 外壳）
<a name="week-examples"></a>

以下示例演示如何使用`$week`运算符检索给定日期的星期数。

**创建示例文档**

```
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") }
]);
```

**查询示例**

```
db.events.aggregate([
  { $project: {
    _id: 1,
    week: { $week: "$date" }
  }}
]);
```

**输出**

```
[
  { "_id": 1, "week": 1 },
  { "_id": 2, "week": 2 },
  { "_id": 3, "week": 53 }
]
```

## 代码示例
<a name="week-code"></a>

要查看使用该`$week`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$year`运算符从日期或时间戳中提取年份部分。

**参数**
+ `expression`：要从中提取年份部分的日期或时间戳表达式。

## 示例（MongoDB 外壳）
<a name="year-examples"></a>

以下示例演示如何使用`$year`运算符从日期字段中提取年份部分。

**创建示例文档**

```
db.events.insertMany([
  { "_id": 1, "date": ISODate("2023-04-15T00:00:00Z") },
  { "_id": 3, "date": ISODate("2021-12-31T00:00:00Z") }
]);
```

**查询示例**

```
db.events.aggregate([
  { $project: { year: { $year: "$date" } } }
]);
```

**输出**

```
[
  { "_id": 1, "year": 2023 },
  { "_id": 3, "year": 2021 }
]
```

## 代码示例
<a name="year-code"></a>

要查看使用该`$year`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$zip`运算符允许您将多个数组组合成单个元组数组（键值对）。当您需要通过合并来自不同源或文档中数组的数据来创建新文档或对象时，这很有用。

**参数**
+ `inputs`：解析为数组的表达式数组。这些数组将被组合成一个元组数组。
+ `useLongestLength`:（可选）如果`true`，则输出数组将具有最长的输入数组的长度，用`null`值填充较短的数组。如果`false`，则输出数组的长度将等于最短的输入数组。
+ `defaults`:（可选）如果相应的输入数组短于最长的输入数组且`useLongestLength`为，则用于元组的默认值数组。`true`

## 示例（MongoDB 外壳）
<a name="zip-examples"></a>

以下示例演示如何使用`$zip`运算符将两个数组组合成单个元组数组。

**创建示例文档**

```
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"]
  }
])
```

**查询示例**

```
db.grades.aggregate([
  {
    $project: {
      "name": 1,
      "scoredClasses": {
        $zip: {
          inputs: ["$scores", "$classes"],
          useLongestLength: true,
          defaults: [null, null]
        }
      }
    }
  }
])
```

**输出**

```
[
  {
    "_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"]
    ]
  }
]
```

## 代码示例
<a name="zip-code"></a>

要查看使用该`$zip`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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()
```

------

# 地理空间
<a name="mongo-apis-geospatial-operators"></a>

本节提供有关 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>

Amazon DocumentDB 中的`$geometry`运算符用于在地理空间查询中指定 GeoJSON 几何对象。此运算符可与其他地理空间查询运算符（如`$geoWithin`和）结合使用`$geoIntersects`，对您的数据执行空间查询。

在亚马逊 DocumentDB 中，`$geometry`运算符支持以下 GeoJSON 几何类型：
+ Point
+ LineString
+ Polygon
+ MultiPoint
+ MultiLineString
+ MultiPolygon
+ GeometryCollection

**参数**
+ `type`: geoJSON 几何对象的类型，例如`Point``Polygon`、等
+ `coordinates`：表示几何形状的坐标数组。坐标数组的结构取决于几何类型。

## 示例（MongoDB 外壳）
<a name="geometry-examples"></a>

以下示例演示如何使用`$geometry`运算符在 Amazon DocumentDB 中执行`$geoIntersects`查询。

**创建示例文档**

```
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]
      ]]
    }
  }
]);
```

**查询示例**

```
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]
        ]]
      }
    }
  }
})
```

**输出**

```
[
  {
    "_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]
        ]
      ]
    }
  }
]
```

## 代码示例
<a name="geometry-code"></a>

要查看使用该`$geometry`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$geoIntersects`运算符用于查找其地理空间数据与指定 GeoJSON 对象相交的文档。对于需要根据文档与给定地理形状（例如多边形或多面）的空间关系来识别文档的应用程序，此运算符非常有用。

**参数**
+ `$geometry`: 一个 GeoJSON 对象，它表示要检查交叉点的形状。支持的 GeoJSON 对象类型有`Point`、`LineString``Polygon`、和。`MultiPolygon`

## 示例（MongoDB 外壳）
<a name="geoIntersects-examples"></a>

以下示例演示如何使用`$geoIntersects`运算符在 Amazon DocumentDB 中查找一组给定坐标的状态名称。

**创建示例文档**

```
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]
      ]]
    }
  }
]);
```

**查询示例**

```
var location = [-73.965355, 40.782865];

db.states.find({
  "loc": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Point",
        "coordinates": location
      }
    }
  }
}, {
  "name": 1
});
```

**输出**

```
{ "_id" : ObjectId("536b0a143004b15885c91a2c"), "name" : "New York" }
```

## 代码示例
<a name="geoIntersects-code"></a>

要查看使用该`$geoIntersects`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$geoWithin`运算符用于查找位置数据（表示为 GeoJSON 对象）完全包含在指定形状（例如多边形或多面）内的文档。这对于查询位于特定地理区域内的对象非常有用。

**参数**
+ `$geometry`: 一个 GeoJSON 对象，它表示要查询的形状。

## 示例（MongoDB 外壳）
<a name="geoWithin-examples"></a>

以下示例演示如何使用`$geoWithin`运算符查找位于纽约州内的所有机场。

**创建示例文档**

```
// 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]
        }
    }
]);
```

**查询示例**

```
var state = db.states.findOne({"name": "New York"});

db.airports.find({
    "loc": {
        "$geoWithin": {
            "$geometry": state.loc
        }
    }
}, {
    "name": 1,
    "type": 1,
    "code": 1,
    "_id": 0
});
```

**输出**

```
[
  {
    "name": "John F. Kennedy International Airport",
    "type": "airport",
    "code": "JFK"
  },
  {
    "name": "LaGuardia Airport",
    "type": "airport",
    "code": "LGA"
  }
]
```

## 代码示例
<a name="geoWithin-code"></a>

要查看使用该`$geoWithin`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$maxDistance`运算符用于指定距离 GeoJSON 点的最大距离（以米为单位），文档必须在该距离之内才能包含在查询结果中。此运算符与运`$nearSphere`算符配合使用以执行地理空间查询。

**参数**
+ `$maxDistance`：距离参考点的最大距离（以米为单位），文档必须在该距离之内才能包含在查询结果中。

## 示例（MongoDB 外壳）
<a name="maxDistance-examples"></a>

以下示例演示如何使用 Amazon DocumentDB 中的`$maxDistance`运算符来查找距离波士顿 100 千米范围内的所有州首府。

**创建示例文档**

```
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] } }
]);
```

**查询示例**

```
db.capitals.find(
  {
    location: {
      $nearSphere: {
        $geometry: { type: "Point", coordinates: [-71.0589, 42.3601] },
        $maxDistance: 100000
      }
    }
  },
  { state: 1, city: 1, _id: 0 }
);
```

**输出**

```
[
  { "state": "Rhode Island", "city": "Providence" },
  { "state": "New Hampshire", "city": "Concord" }
]
```

## 代码示例
<a name="maxDistance-code"></a>

要查看使用该`$maxDistance`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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`是与`$nearSphere`或`$geoNear`结合使用的查找运算符，用于筛选距离中心点至少达到指定最小距离的文档。该运算符在 Amazon DocumentDB 中受支持，其功能与 MongoDB 中的对应运算符类似。

**参数**
+ `$minDistance`：从中心点到结果中包含文档的最小距离（以米为单位）。

## 示例（MongoDB 外壳）
<a name="minDistance-examples"></a>

在此示例中，我们将找到华盛顿州西雅图特定地点 2 公里半径范围内的所有餐厅。

**创建示例文档**

```
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]
    }
  }
]);
```

**查询示例**

```
db.usarestaurants.find({
  "location": {
    "$nearSphere": {
      "$geometry": {
        "type": "Point",
        "coordinates": [-122.3516, 47.6156]
      },
      "$minDistance": 1,
      "$maxDistance": 2000
    }
  }
}, {
  "name": 1
});
```

**输出**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## 代码示例
<a name="minDistance-code"></a>

要查看使用该`$minDistance`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$near`运算符用于查找地理位置靠近指定点的文档。它返回按距离排序的文档，最接近的文档排在最前面。此运算符需要 2dsphere 地理空间索引，可用于位置数据的邻近查询。

**参数**
+ `$geometry`: 一个 GeoJSON 点对象，用于定义近距离查询的中心点。
+ `$maxDistance`:（可选）文档与查询相匹配的最大距离（以米为单位）。
+ `$minDistance`:（可选）文档与查询相匹配的最小距离（以米为单位）。

**索引要求**
+ `2dsphere index`：对 GeoJSON 点数据进行地理空间查询所必需的。

## 示例（MongoDB 外壳）
<a name="near-examples"></a>

以下示例演示如何使用`$near`运算符查找距离华盛顿州西雅图特定地点最近的餐厅。

**创建示例文档**

```
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] }
  }
]);
```

**创建 2dsphere 索引**

```
db.usarestaurants.createIndex({ "location": "2dsphere" });
```

**使用 geoJSON 点查询示例**

```
db.usarestaurants.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $maxDistance: 100,
      $minDistance: 10
    }
  }
});
```

**输出**

```
{
  "_id" : ObjectId("69031ec9ea1c2922a1ce5f4a"),
  "name" : "Noodle House",
  "city" : "Seattle",
  "state" : "Washington",
  "rating" : 4.8,
  "location" : {
    "type" : "Point",
    "coordinates" : [ -122.3517, 47.6159 ]
  }
}
```

## 代码示例
<a name="near-code"></a>

要查看使用该`$near`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$nearSphere`运算符用于查找距离地理空间点指定距离内的文档。此运算符对于地理空间查询特别有用，例如查找给定位置一定半径范围内的所有餐厅。

**参数**
+ `$geometry`: 表示参考点的 GeoJSON 对象。必须是带有`type`和`coordinates`字段的`Point`对象。
+ `$minDistance`:（可选）文档必须位于的参考点的最小距离（以米为单位）。
+ `$maxDistance`:（可选）从文档必须位于的参考点的最大距离（以米为单位）。

## 示例（MongoDB 外壳）
<a name="nearSphere-examples"></a>

在此示例中，我们将找到距离华盛顿州西雅图特定地点 2 千米（2000 米）范围内的所有餐厅。

**创建示例文档**

```
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] }
  }
]);
```

**查询示例**

```
db.usarestaurants.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $minDistance: 1,
      $maxDistance: 2000
    }
  }
}, {
  name: 1
});
```

**输出**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## 代码示例
<a name="nearSphere-code"></a>

要查看使用该`$nearSphere`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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()
```

------

# 查询和投影运算符
<a name="mongo-apis-query-projection-operators"></a>

本节提供有关 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>

`$`投影运算符将数组字段的内容限制为仅返回与查询条件匹配的第一个元素。它用于投影单个匹配的数组元素。

**参数**
+ `field.$`: 带有位置运算符的数组字段，用于投影第一个匹配的元素。

## 示例（MongoDB 外壳）
<a name="dollar-projection-examples"></a>

以下示例演示了使用`$`投影运算符仅返回匹配的数组元素。

**创建示例文档**

```
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] }
]);
```

**查询示例**

```
db.students.find(
  { grades: { $gte: 90 } },
  { name: 1, "grades.$": 1 }
);
```

**输出**

```
{ "_id" : 1, "name" : "Alice", "grades" : [ 92 ] }
{ "_id" : 2, "name" : "Bob", "grades" : [ 92 ] }
{ "_id" : 3, "name" : "Charlie", "grades" : [ 95 ] }
```

在此示例中，仅返回每个学生大于或等于 90 的一年级成绩。

## 代码示例
<a name="dollar-projection-code"></a>

要查看使用`$`投影运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$all`运算符用于匹配其中字段值为数组且包含所有指定元素的文档，无论数组中元素的顺序如何。

**参数**
+ `field`：要检查的字段的名称。
+ `[value1, value2, ...]`：数组中要匹配的值列表。

 

**在`$all`表达式`$elemMatch`中使用**

有关在`$all`表达式中使用`$elemMatch`运算符的限制，请参阅[在 `$all` 表达式中使用 `$elemMatch`](functional-differences.md#functional-differences.elemMatch)。

 

**字段名称中的美元 (\$1)**

有关在嵌套对象中查询`$`前缀字段的限制`$all`，请参阅[字段名称中的美元符号（\$1）和句点（.）](functional-differences.md#functional-differences-dollardot)。

## 示例（MongoDB 外壳）
<a name="all-examples"></a>

以下示例演示如何使用`$all`运算符来检索文档，其中 “颜色” 字段是一个同时包含 “红色” 和 “蓝色” 的数组。

**创建示例文档**

```
db.example.insertMany([
  { "Item": "Pen", "Colors": ["Red", "Blue", "Green"] },
  { "Item": "Notebook", "Colors": ["Blue", "White"] },
  { "Item": "Poster Paint", "Colors": ["Red", "Yellow", "White"] }
])
```

**查询示例**

```
db.example.find({ "Colors": { $all: ["Red", "Blue"] } }).pretty()
```

**输出**

```
{
  "_id" : ObjectId("6137d6c5b3a1d35e0b6ee6ad"),
  "Item" : "Pen",
  "Colors" : [ 
          "Red", 
          "Blue", 
          "Green" 
  ]
}
```

## 代码示例
<a name="all-code"></a>

要查看使用该`$all`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$and`运算符用于组合多个表达式并将其作为单个条件进行评估。`true`如果所有提供的表达式的计算结果均为，则返回`true`，`false`否则返回。此运算符对于将多个条件应用于查询很有用。

**参数**
+ `expression1`：计算结果为布尔值的必填表达式。
+ `expression2`：计算结果为布尔值的必填表达式。
+ `...`：计算结果为布尔值的其他必需表达式。

## 示例（MongoDB 外壳）
<a name="and-examples"></a>

以下示例演示如何使用`$and`运算符查找 “用户” 集合中的所有文档，其中 “年龄” 字段大于 18 且 “状态” 字段为 “活动”。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.users.find({
  $and: [
    { age: { $gt: 18 } },
    { status: "active" }
  ]
});
```

**输出**

```
[
  { "_id" : ObjectId("614e3c4b63f5892e7c4e2345"), "name" : "John", "age" : 25, "status" : "active" },
  { "_id" : ObjectId("614e3c4b63f5892e7c4e2347"), "name" : "Alice", "age" : 22, "status" : "active" }
]
```

## 代码示例
<a name="and-code"></a>

要查看使用该`$and`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$bitsAllClear`运算符用于匹配已清除字段中所有指定位（设置为 0）的文档。此运算符可用于对存储的数据执行按位运算。

**参数**
+ `field`：用于检查指定位是否被清除的字段。
+ `value`：指定应检查哪些位的数字位掩码，或要检查的位位置列表。数字位掩码可以是二进制 (0b...)、十进制、十六进制 (0x...)、八进制 (0o...) 或二进制 () 形式。BinData在位位置列表中，最低有效位的位置为 0。

## 示例（MongoDB 外壳）
<a name="bitsAllClear-examples"></a>

以下示例演示了`$bitsAllClear`运算符在 Amazon DocumentDB 中的用法。

**创建示例文档**

```
db.collection.insertMany([
  { _id: 1, bits: 0b1010 },
  { _id: 2, bits: 0b1100 },
  { _id: 3, bits: 0b0101 }
]);
```

**查询示例**

```
db.collection.find({
  bits: { $bitsAllClear: 0b0011 }
})
```

**输出**

```
{ "_id" : 2, "bits" : 12 }
```

该查询会检查`bits`字段中是否清除了位掩码指定的所有位`0b0011`（两个最低有效位）。带有 `_id` 2 的文档满足此条件，因为其`bits`字段已清除这些位。

## 代码示例
<a name="bitsAllClear-code"></a>

要查看使用该`$bitsAllClear`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$bitsAllSet`运算符用于查询字段中特定位集全部设置为 1 的文档。此运算符允许您对字段值执行按位运算，并且在需要检查数值中各个位的状态时非常有用。

**参数**
+ `field`：要对其执行按位运算的数值字段的名称。
+ `value`：指定应检查哪些位的数字位掩码，或要检查的位位置列表。数字位掩码可以是二进制 (0b...)、十进制、十六进制 (0x...)、八进制 (0o...) 或二进制 () 形式。BinData在位位置列表中，最低有效位的位置为 0。

## 示例（MongoDB 外壳）
<a name="bitsAllSet-examples"></a>

以下示例演示如何使用`$bitsAllSet`运算符来查找该`flags`字段设置了由位掩码指定的所有位的文档。

**创建示例文档**

```
db.collection.insert([
  { _id: 1, flags: 0b1010 },
  { _id: 2, flags: 0b1100 },
  { _id: 3, flags: 0b1110 }
])
```

**查询示例**

```
db.collection.find({ flags: { $bitsAllSet: 0b1100 } })
```

**输出**

```
{ "_id": 2, "flags": 12 },
{ "_id": 3, "flags": 14 }
```

在此示例中，查询会检查`flags`字段中是否包含由位掩码`0b1100`（表示十进制值 12）指定的所有位的文档。带有 `_id` 2 和 3 的文档符合此标准，因为它们的`flags`字段值设置了所有必需的位（第 3 和第 4 个最低有效位）。

## 代码示例
<a name="bitsAllSet-code"></a>

要查看使用该`$bitsAllSet`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$bitsAnyClear`运算符用于匹配清除字段中任何指定位（设置为 0）的文档。这对于对存储在文档中的字段值执行按位运算很有用。

**参数**
+ `field`：要检查的字段。
+ `value`：指定应检查哪些位的数字位掩码，或要检查的位位置列表。数字位掩码可以是二进制 (0b...)、十进制、十六进制 (0x...)、八进制 (0o...) 或二进制 () 形式。BinData在位位置列表中，最低有效位的位置为 0。

## 示例（MongoDB 外壳）
<a name="bitsAnyClear-examples"></a>

以下示例演示如何使用`$bitsAnyClear`运算符来检查`items`集合`status`字段中是否有任何位被清除。

**创建示例文档**

```
db.items.insertMany([
  { "_id": 1, "status": 7 },
  { "_id": 2, "status": 15 },
  { "_id": 3, "status": 31 }
]);
```

**查询示例**

```
db.items.find({ "status": { $bitsAnyClear: 8 } })
```

**输出**

```
{ "_id" : 1, "status" : 7 }
```

在此示例中，该查询会检查该`status`字段在位掩码（二进制）中是否有清除位 `8` (0`1000`) 的文档。`status`值为`7`（二进制`111`）的文档与查询相匹配，因为它在提供的位掩码中至少有一个空位。匹配的清除位是第 4 个最低有效位。

## 代码示例
<a name="bitsAnyClear-code"></a>

要查看使用该`$bitsAnyClear`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$bitsAnySet`运算符用于查询字段中指定位中至少有一个位设置为 1 的文档。此运算符允许您对存储在字段中的值执行按位运算，从而可以高效查询和分析具有按位特征的数据。

**参数**
+ `field`：要应用按位运算的字段名称。
+ `value`：指定应检查哪些位的数字位掩码，或要检查的位位置列表。数字位掩码可以是二进制 (0b...)、十进制、十六进制 (0x...)、八进制 (0o...) 或二进制 () 形式。BinData在位位置列表中，最低有效位的位置为 0。

## 示例（MongoDB 外壳）
<a name="bitsAnySet-examples"></a>

以下示例演示如何使用`$bitsAnySet`运算符查找`flags`字段中至少设置了一个位的文档。

**创建示例文档**

```
db.collection.insertMany([
  { _id: 1, flags: 0b1010 },
  { _id: 2, flags: 0b1100 },
  { _id: 3, flags: 0b0011 },
  { _id: 4, flags: 0b0100 }
]);
```

**查询示例**

```
db.collection.find({
  flags: { $bitsAnySet: 0b1010 }
})
```

**输出**

```
{ "_id" : 1, "flags" : 10 }
{ "_id" : 2, "flags" : 12 }
{ "_id" : 3, "flags" : 3 }
```

该查询返回的文档中，该`flags`字段中至少设置了`0b1010`位掩码中指定的一个位。

## 代码示例
<a name="bitsAnySet-code"></a>

要查看使用该`$bitsAnySet`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$comment`运算符用于为查询添加注释。这对于提供有关查询的其他上下文或信息很有用，这可能有助于调试或记录目的。所附注释将作为诸如 db.currenTop () 之类的操作输出的一部分出现。

**参数**
+ `string`：查询所附的评论。

## 示例（MongoDB 外壳）
<a name="comment-examples"></a>

以下示例演示了如何在 Amazon DocumentDB 中使用`$comment`运算符。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.users.find({ age: { $gt: 25 } }, { _id: 0, name: 1, age: 1 }).comment("Retrieve users older than 25");
```

**输出**

```
{ "name" : "John Doe", "age" : 30 }
{ "name" : "Bob Johnson", "age" : 35 }
```

## 代码示例
<a name="comment-code"></a>

要查看使用该`$comment`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$elemMatch`运算符用于查询数组字段，并返回数组中至少有一个元素符合指定条件的文档。当您拥有包含嵌套数组或嵌入式文档的复杂数据结构时，此运算符特别有用。

Planner 版本 2.0 添加了对索引的支持`$elemMatch`。

**参数**
+ `field`：要查询的数组字段。
+ `query`：与数组元素匹配的标准。

 

**在`$all`表达式`$elemMatch`中使用**

有关在`$all`表达式中使用`$elemMatch`运算符的限制，请参阅[在 `$all` 表达式中使用 `$elemMatch`](functional-differences.md#functional-differences.elemMatch)。

## 示例（MongoDB 外壳）
<a name="elemMatch-examples"></a>

以下示例演示如何使用`$elemMatch`运算符来查找`parts`数组中至少有一个符合指定条件的元素的文档。

**创建示例文档**

```
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 }] }
]);
```

**查询示例**

```
db.col.find({
  parts: { "$elemMatch": { part: "xyz", qty: { $lt: 11 } } }
})
```

**输出**

```
{ "_id" : 1, "parts" : [ { "part" : "xyz", "qty" : 10 }, { "part" : "abc", "qty" : 20 } ] }
{ "_id" : 2, "parts" : [ { "part" : "xyz", "qty" : 5 }, { "part" : "abc", "qty" : 10 } ] }
```

## 代码示例
<a name="elemMatch-code"></a>

要查看使用该`$elemMatch`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$eq`运算符用于匹配字段值等于指定值的文档。该运算符通常用于检索符合指定条件的文档`find()`的方法。

**参数**
+ `field`：要检查相等条件的字段。
+ `value`：要与字段进行比较的值。

## 示例（MongoDB 外壳）
<a name="eq-examples"></a>

以下示例演示如何使用`$eq`运算符来查找该`name`字段等于的所有文档`"Thai Curry Palace"`。

**创建示例文档**

```
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"] }
]);
```

**查询示例**

```
db.restaurants.find({ name: { $eq: "Thai Curry Palace" } });
```

**输出**

```
{ "_id" : ObjectId("68ee586f916df9d39f3d9414"), "name" : "Thai Curry Palace", "cuisine" : "Thai", "features" : [ "Private Dining" ] }
```

## 代码示例
<a name="eq-code"></a>

要查看使用该`$eq`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$exists`运算符用于检查文档中是否存在字段。 `$exists`在 Amazon DocumentDB 中处理稀疏索引时特别有用，因为索引字段可能不会出现在所有文档中。

要使用您在查询中创建的稀疏索引，必须在涵盖索引的字段中使用 `$exists` 子句。如果省略`$exists`，Amazon DocumentDB 将不会使用稀疏索引进行查询。

**参数**
+ `field`：要检查是否存在的字段名称。
+ `value`：一个布尔值（`true`或`false`），用于指定匹配文档中该字段是否应存在 (`true``false`) 还是不存在 ()。

## 示例（MongoDB 外壳）
<a name="exists-examples"></a>

以下示例演示了如何在`food`集合中的`special_diets`字段上使用带有稀疏索引的`$exists`运算符。

**创建示例文档**

```
db.food.insertMany([
  { _id: 1, name: "Apple", special_diets: ["vegetarian", "gluten-free"] },
  { _id: 2, name: "Broccoli" },
  { _id: 3, name: "Chicken", special_diets: ["dairy-free"] }
]);
```

**在 “special\$1diets” 字段上创建稀疏索引**

```
db.food.createIndex({ "special_diets": 1 }, { sparse: true, name: "special_diets_sparse_asc" });
```

**查询示例**

```
db.food.find({ "special_diets": { $exists: true } });
```

**输出**

```
[
  { "_id" : 1, "name" : "Apple", "special_diets" : [ "vegetarian", "gluten-free" ] },
  { "_id" : 3, "name" : "Chicken", "special_diets" : [ "dairy-free" ] }
]
```

## 代码示例
<a name="exists-code"></a>

要查看使用该`$exists`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的`$expr`运算符允许您在查询语言中使用聚合表达式。它使您能够对文档中的字段执行复杂的比较和计算，类似于使用聚合管道阶段的方式。

**参数**
+ `expression`：返回布尔值的表达式，允许您对文档字段执行比较和计算。

## 示例（MongoDB 外壳）
<a name="expr-examples"></a>

以下示例演示如何使用`$expr`运算符来查找`manufacturingCost`字段大于该`price`字段的所有文档。

**创建示例文档**

```
db.inventory.insertMany([
  { item: "abc", manufacturingCost: 500, price: 100 },
  { item: "def", manufacturingCost: 300, price: 450 },
  { item: "ghi", manufacturingCost: 400, price: 120 }
]);
```

**查询示例**

```
db.inventory.find({
  $expr: {
    $gt: ["$manufacturingCost", "$price"]
  }
})
```

**输出**

```
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89a"), "item" : "abc", "manufacturingCost" : 500, "price" : 100 },
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89c"), "item" : "ghi", "manufacturingCost" : 400, "price" : 120 }
```

## 代码示例
<a name="expr-code"></a>

要查看使用该`$expr`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$gt`运算符用于选择指定字段值大于指定值的文档。此运算符可用于根据数值比较筛选和查询数据。

**参数**
+ `field`：要比较的字段。
+ `value`：要比较的值。

## 示例（MongoDB 外壳）
<a name="gt-examples"></a>

以下示例演示如何使用`$gt`运算符查找`age`字段大于 30 的所有文档。

**创建示例文档**

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

**查询示例**

```
db.users.find({ age: { $gt: 30 } });
```

**输出**

```
{ "_id" : ObjectId("6249e5c22a5d39884a0a0001"), "name" : "Jane", "age" : 32 },
{ "_id" : ObjectId("6249e5c22a5d39884a0a0002"), "name" : "Bob", "age" : 45 }
```

## 代码示例
<a name="gt-code"></a>

要查看使用该`$gt`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$gte`运算符用于匹配大于或等于指定值的值。此运算符可用于根据数值比较筛选和查询数据。

**参数**
+ `field`：要根据提供的值进行检查的字段。
+ `value`：要与字段进行比较的值。

## 示例（MongoDB 外壳）
<a name="gte-examples"></a>

以下示例演示如何在 Amazon DocumentDB 中使用`$gte`运算符来查找 “年龄” 字段大于或等于 25 的所有文档。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.users.find({ age: { $gte: 25 } }, { _id: 0, name: 1, age: 1 });
```

**输出**

```
{ "name" : "Jane", "age" : 25 }
{ "name" : "Bob", "age" : 30 }
{ "name" : "Alice", "age" : 35 }
```

## 代码示例
<a name="gte-code"></a>

要查看使用该`$gte`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的运算符是一种逻辑查询运算符，它允许您查找字段值等于数组中指定的任何值的文档。`$in`

**参数**
+ `field`：要对照提供的数组进行检查的字段。
+ `[value1, value2, ...]`：要与指定字段匹配的值数组。

 

**字段名称中的美元 (`$`)**

有关在嵌套对象中查询`$`前缀字段的限制`$in`，请参阅[字段名称中的美元符号（\$1）和句点（.）](functional-differences.md#functional-differences-dollardot)。

## 示例（MongoDB 外壳）
<a name="in-examples"></a>

以下示例演示如何使用`$in`运算符来查找该`color`字段是所提供数组中值之一的文档。

**创建示例文档**

```
db.colors.insertMany([
  { "_id": 1, "color": "red" },
  { "_id": 2, "color": "green" },
  { "_id": 3, "color": "blue" },
  { "_id": 4, "color": "yellow" },
  { "_id": 5, "color": "purple" }
])
```

**查询示例**

```
db.colors.find({ "color": { "$in": ["red", "blue", "purple"] } })
```

**输出**

```
{ "_id": 1, "color": "red" },
{ "_id": 3, "color": "blue" },
{ "_id": 5, "color": "purple" }
```

## 代码示例
<a name="in-code"></a>

要查看使用该`$in`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

4.0 版的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的`$jsonSchema`运算符用于根据指定的 JSON 架构筛选文档。此运算符允许您查询与特定 JSON 架构匹配的文档，确保检索到的文档符合特定的结构和数据类型要求。

在创建集合时使用`$jsonSchema`评估查询运算符，可以验证插入到集合中的文档的架构。有关更多信息，请参阅[使用 JSON 架构验证](json-schema-validation.md)。

**参数**
+ `required`（数组）：指定文档中的必填字段。
+ `properties`（object）：定义文档中每个字段的数据类型和其他约束。

## 示例（MongoDB 外壳）
<a name="jsonSchema-examples"></a>

以下示例演示如何使用`$jsonSchema`运算符筛选`employees`集合，以仅检索具有`name`、`employeeId`和`age`字段且`employeeId`字段类型为的文档`string`。

**创建示例文档**

```
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" }
]);
```

**查询示例**

```
db.employees.aggregate([
  { $match: {
    $jsonSchema: {
      required: ["name", "employeeId", "age"],
      properties: { "employeeId": { "bsonType": "string" } }
    }
  }}
]);
```

**输出**

```
{ "_id" : ObjectId("6908e8b61f77fc26b2ecd26f"), "name" : { "firstName" : "Emily", "lastName" : "Brown" }, "employeeId" : "2", "age" : 25 }
```

## 代码示例
<a name="jsonSchema-code"></a>

要查看使用该`$jsonSchema`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$lt`运算符用于匹配小于指定值的值。此运算符可用于根据数值比较筛选和查询数据。

**参数**
+ `field`：要检查的字段名称。
+ `value`：要比较的值。

## 示例（MongoDB 外壳）
<a name="lt-examples"></a>

以下示例演示如何使用`$lt`运算符检索`Inventory.OnHand`值小于 50 的文档。

**创建示例文档**

```
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"] }
]);
```

**查询示例**

```
db.example.find({ "Inventory.OnHand": { $lt: 50 } })
```

**输出**

```
{ "_id" : 1, "Inventory" : { "OnHand" : 25, "Sold" : 60 }, "Colors" : [ "Red", "Blue" ] }
{ "_id" : 3, "Inventory" : { "OnHand" : 10, "Sold" : 85 }, "Colors" : [ "Red", "Green" ] }
```

## 代码示例
<a name="lt-code"></a>

要查看使用该`$lt`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$mod`查询运算符选择字段值除以除数具有指定余数的文档。这对于根据模算术条件筛选文档很有用。

**参数**
+ `divisor`: 要除以的数字。
+ `remainder`：预期的剩余值。

## 示例（MongoDB 外壳）
<a name="mod-query-examples"></a>

以下示例演示如何使用`$mod`运算符查找数量为奇数的所有订单。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.orders.find({ quantity: { $mod: [2, 1] } });
```

**输出**

```
{ "_id" : 1, "item" : "Widget", "quantity" : 15 }
{ "_id" : 3, "item" : "Tool", "quantity" : 7 }
{ "_id" : 5, "item" : "Part", "quantity" : 9 }
```

此查询返回的文档中，数量除以 2 的余数为 1，实际上选择了所有奇数。

## 代码示例
<a name="mod-query-code"></a>

要查看使用`$mod`查询运算符的代码示例，请选择要使用的语言对应的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$lte`运算符用于匹配指定字段值小于或等于指定值的文档。此运算符对于根据数值比较筛选和查询数据非常有用。

**参数**
+ `field`：要比较的字段。
+ `value`：要比较的值。

## 示例（MongoDB 外壳）
<a name="lte-examples"></a>

以下示例演示如何使用`$lte`运算符来检索`quantity`字段小于或等于 10 的文档。

**创建示例文档**

```
db.inventory.insertMany([
  { item: "canvas", qty: 100 },
  { item: "paint", qty: 50 },
  { item: "brush", qty: 10 },
  { item: "paper", qty: 5 }
]);
```

**查询示例**

```
db.inventory.find({ qty: { $lte: 10 } });
```

**输出**

```
{ "_id" : ObjectId("..."), "item" : "brush", "qty" : 10 },
{ "_id" : ObjectId("..."), "item" : "paper", "qty" : 5 }
```

## 代码示例
<a name="lte-code"></a>

要查看使用该`$lte`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$meta`运算符用于访问与当前查询执行相关的元数据。此运算符主要用于文本搜索操作，其中元数据可以提供有关匹配文档相关性的信息。

**参数**
+ `textScore`：检索文档的文本搜索分数。该分数表示文档与文本搜索查询的相关性。

## 示例（MongoDB 外壳）
<a name="meta-examples"></a>

以下示例演示如何使用`$meta`运算符检索与文本搜索查询相匹配的文档的文本搜索分数。

**创建示例文档**

```
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." }
]);
```

**创建文本索引**

```
db.documents.createIndex({ content: "text" });
```

**查询示例**

```
db.documents.find(
  { $text: { $search: "coffee" } },
  { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });
```

**输出**

```
[
  {
    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
  }
]
```

## 代码示例
<a name="meta-code"></a>

要查看使用该`$meta`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$ne`运算符用于匹配字段值不等于指定值的文档。它是一个比较运算符，可以在查询谓词中用于筛选文档。

Planner 版本 2.0 添加了对索引的支持`$ne`。

**参数**
+ `field`：要检查的字段。
+ `value`：要检查的值。

## 示例（MongoDB 外壳）
<a name="ne-examples"></a>

在此示例中，我们将查找`users`集合中该`status`字段不等于的所有文档`"active"`。

**创建示例文档**

```
db.users.insertMany([
  { name: "John", status: "active" },
  { name: "Jane", status: "inactive" },
  { name: "Bob", status: "suspended" },
  { name: "Alice", status: "active" }
]);
```

**查询示例**

```
db.users.find({ status: { $ne: "active" } });
```

**输出**

```
[
  {
    _id: ObjectId('...'),
    name: 'Jane',
    status: 'inactive'
  },
  {
    _id: ObjectId('...'),
    name: 'Bob',
    status: 'suspended'
  }
]
```

## 代码示例
<a name="ne-code"></a>

要查看使用该`$ne`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$nin`运算符用于匹配不在指定数组中的值。它是`$in`运算符的倒数，它匹配指定数组中的值。

Planner 版本 2.0 添加了对索引的支持`$nin`。

**参数**
+ `field`：要检查的字段。
+ `array`：要检查的值数组。

 

**字段名称中的美元 (`$`)**

有关在嵌套对象中查询`$`前缀字段的限制`$nin`，请参阅[字段名称中的美元符号（\$1）和句点（.）](functional-differences.md#functional-differences-dollardot)。

## 示例（MongoDB 外壳）
<a name="nin-examples"></a>

以下示例演示如何使用`$nin`运算符来查找`category`字段不等于 “虚构” 或 “神秘” 的文档。

**创建示例文档**

```
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" }
])
```

**查询示例**

```
db.books.find({
  category: {
    $nin: ["Fiction", "Mystery"]
  }
})
```

**输出**

```
[
  {
    _id: ObjectId('...'),
    title: 'The Martian',
    author: 'Andy Weir',
    category: 'Science Fiction'
  },
  {
    _id: ObjectId('...'),
    title: 'The Alchemist',
    author: 'Paulo Coelho',
    category: 'Philosophy'
  }
]
```

## 代码示例
<a name="nin-code"></a>

要查看使用该`$nin`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$nor`运算符用于匹配所有指定查询条件均不为真的文档。它类似于逻辑 “NOR” 运算，如果所有操作数都不为真，则结果为真。

**参数**
+ `expression1`：要计算的第一个表达式。
+ `expression2`：要计算的第二个表达式。
+ `expressionN`：其他要评估的表达式。

## 示例（MongoDB 外壳）
<a name="nor-examples"></a>

以下示例通过检索字段不小于 20 且`qty`字段不等于 “XL” 的文档来演示`$nor`运算符的用法。`size`

**创建示例文档**

```
db.items.insertMany([
  { qty: 10, size: "M" },
  { qty: 15, size: "XL" },
  { qty: 25, size: "L" },
  { qty: 30, size: "XL" }
])
```

**查询示例**

```
db.items.find({
  $nor: [
    { qty: { $lt: 20 } },
    { size: "XL" }
  ]
})
```

**输出**

```
[
  { "_id" : ObjectId("..."), "qty" : 25, "size" : "L" }
]
```

## 代码示例
<a name="nor-code"></a>

要查看使用该`$nor`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$not`运算符用于否定给定表达式的结果。它允许您选择与指定条件不匹配的文档。

Planner 版本 2.0 增加了对`$not {eq}`和的索引支持`$not {in}`。

**参数**
+ `expression`: 要否定的表达式。

## 示例（MongoDB 外壳）
<a name="not-examples"></a>

以下示例演示如何使用`$not`运算符来查找`status`字段不等于 “active” 的文档。

**创建示例文档**

```
db.users.insertMany([
  { name: "John", status: "active" },
  { name: "Jane", status: "inactive" },
  { name: "Bob", status: "pending" },
  { name: "Alice", status: "active" }
]);
```

**查询示例**

```
db.users.find({ status: { $not: { $eq: "active" } } });
```

**输出**

```
[
  {
    _id: ObjectId('...'),
    name: 'Jane',
    status: 'inactive'
  },
  {
    _id: ObjectId('...'),
    name: 'Bob',
    status: 'pending'
  }
]
```

## 代码示例
<a name="not-code"></a>

要查看使用该`$not`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$or`运算符用于对包含两个或更多表达式的数组执行逻辑 OR 运算。它返回至少与其中一个表达式匹配的文档。当您需要查询满足多个条件中任意一个的文档时，此运算符很有用。

**参数**
+ `expression1`：要计算的第一个表达式。
+ `expression2`：要计算的第二个表达式。
+ `...`：要评估的其他表达式（可选）。

## 示例（MongoDB 外壳）
<a name="or-examples"></a>

以下示例演示了如何使用`$or`运算符来查找文档，其中模型为 “H `make` eavy H1TruckForYou” 时为 “”，或者模型为 “Bolid 1SportForYou” 时为 “”。

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.cars.find({
  $or: [
    { make: "TruckForYou", model: "Heavy H1" },
    { make: "SportForYou", model: "Bolid 1" }
  ]
});
```

**输出**

```
[
  {
    _id: ObjectId('...'),
    make: 'TruckForYou',
    model: 'Heavy H1',
    year: 2020
  },
  {
    _id: ObjectId('...'),
    make: 'SportForYou',
    model: 'Bolid 1',
    year: 2021
  }
]
```

## 代码示例
<a name="or-code"></a>

要查看使用该`$or`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$regex`运算符允许您对字符串字段执行正则表达式匹配。它是基于复杂模式搜索和筛选文档的强大工具。

**参数**
+ `regular expression`：要与字段匹配的正则表达式模式。
+ `$options`:（可选）提供修改搜索行为的选项，例如区分大小写、全局匹配等。

## 示例（MongoDB 外壳）
<a name="regex-examples"></a>

以下示例演示如何使用`$regex`运算符来搜索 “名称” 字段与特定模式匹配的文档。

**创建示例文档**

```
db.users.insertMany([
  { name: "John Doe" },
  { name: "Jane Smith" },
  { name: "Alice Johnson" },
  { name: "Bob Williams" },
  { name: "Charlie Davis" }
]);
```

**查询示例**

```
db.users.find({ name: { $regex: /^A/ } })
```

**输出**

```
[
  { "_id" : ObjectId("..."), "name" : "Alice Johnson" }
]
```

此查询将返回 “名称” 字段以字母 “A” 开头的所有文档。

## 代码示例
<a name="regex-code"></a>

要查看使用该`$regex`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$slice`投影运算符限制查询结果中返回的数组元素的数量。它允许您从数组字段的开头或结尾检索特定数量的元素，而无需加载整个数组。

**参数**
+ `field`：要投影的数组字段。
+ `count`：要返回的元素数量。正值从一开始返回元素，从结尾返回负值。

## 示例（MongoDB 外壳）
<a name="slice-projection-examples"></a>

以下示例演示如何使用`$slice`投影运算符仅返回数组字段中的前两项。

**创建示例文档**

```
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"] }
]);
```

**查询示例**

```
db.inventory.find(
  {},
  { item: 1, tags: { $slice: 2 } }
)
```

**输出**

```
{ "_id" : 1, "item" : "notebook", "tags" : [ "office", "school" ] }
{ "_id" : 2, "item" : "pen", "tags" : [ "office", "writing" ] }
{ "_id" : 3, "item" : "folder", "tags" : [ "office", "supplies" ] }
```

## 代码示例
<a name="slice-projection-code"></a>

要查看使用`$slice`投影运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$size`查询运算符匹配数组字段具有精确指定数量的元素的文档。这对于根据数组长度筛选文档很有用。

**参数**
+ `field`：要检查的数组字段。
+ `count`：数组必须包含的元素的确切数量。

## 示例（MongoDB 外壳）
<a name="size-query-examples"></a>

以下示例演示如何使用`$size`运算符查找恰好具有三个标签的所有产品。

**创建示例文档**

```
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"] }
]);
```

**查询示例**

```
db.products.find({ tags: { $size: 3 } });
```

**输出**

```
{ "_id" : 1, "name" : "Laptop", "tags" : [ "electronics", "computers", "portable" ] }
{ "_id" : 3, "name" : "Desk", "tags" : [ "furniture", "office", "workspace" ] }
```

## 代码示例
<a name="size-query-code"></a>

要查看使用`$size`查询运算符的代码示例，请选择要使用的语言对应的选项卡：

------
#### [ 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>

该`$text`运算符用于对文档集合中的文本索引字段执行全文搜索。此运算符允许您搜索包含特定单词或短语的文档，并且可以与其他查询运算符结合使用以根据其他条件筛选结果。

**参数**
+ `$search`：要搜索的文本字符串。

## 示例（MongoDB 外壳）
<a name="text-examples"></a>

以下示例演示如何使用`$text`运算符搜索包含 “兴趣” 一词的文档，并根据 “star\$1rating” 字段筛选结果。

**创建示例文档**

```
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" }
]);
```

**创建文本索引**

```
db.test.createIndex({ comments: "text" });
```

**查询示例**

```
db.test.find({$and: [{star_rating: 5}, {$text: {$search: "interest"}}]})
```

**输出**

```
{ "_id" : 5, "star_rating" : 5, "comments" : "interesting couch" }
{ "_id" : 6, "star_rating" : 5, "comments" : "interested in couch for sale, year 2022" }
```

上面的命令返回的文档的文本索引字段包含任何形式的 “兴趣”，“star\$1rating” 等于 5。

## 代码示例
<a name="text-code"></a>

要查看使用该`$text`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

运`$type`算符用于检查文档中字段的数据类型。它可以在需要特定于类型的操作或验证时使用。运`$type`算符返回已计算表达式的 BSON 类型。返回的类型是一个字符串，它对应于字段或表达式的类型。

Planner 版本 2.0 增加了对索引的支持`$type`。

**参数**
+ `expression`：要计算的表达式。

## 示例（MongoDB 外壳）
<a name="type-examples"></a>

**创建示例文档**

```
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 }
]);
```

**查询示例**

```
db.documents.find({
  $or: [
    { age: { $type: "number" } },
    { email: { $type: "string" } },
    { name: { $type: "string" } }
  ]
})
```

**输出**

```
[
  { "_id": 1, "name": "John", "age": 30, "email": "john@example.com" },
  { "_id": 2, "name": "Jane", "age": "25", "email": 123456 }
]
```

此查询将返回`age`字段类型为 “数字”、`email`字段类型为 “字符串”、`name`字段类型为 “字符串” 的文档。

## 代码示例
<a name="type-code"></a>

要查看使用该`$type`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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()
```

------

# 更新运算符
<a name="mongo-apis-update-operators"></a>

本节提供有关亚马逊 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>

`$`位置运算符更新第一个匹配查询条件的数组元素。它充当匹配数组元素位置的占位符。

**参数**
+ `field.$`: 带有位置运算符的数组字段，用于更新第一个匹配的元素。

## 示例（MongoDB 外壳）
<a name="dollar-update-examples"></a>

以下示例演示了使用`$`位置运算符来更新特定的数组元素。

**创建示例文档**

```
db.inventory.insertMany([
  { _id: 1, item: "Widget", quantities: [10, 20, 30] },
  { _id: 2, item: "Gadget", quantities: [5, 15, 25] }
]);
```

**查询示例**

```
db.inventory.updateOne(
  { _id: 1, quantities: 20 },
  { $set: { "quantities.$": 22 } }
);
```

**输出**

```
{
  "_id" : 1,
  "item" : "Widget",
  "quantities" : [ 10, 22, 30 ]
}
```

## 代码示例
<a name="dollar-update-code"></a>

要查看使用`$`位置运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

al `$[]` l 位置运算符更新数组中的所有元素。当你需要修改数组字段中的每个元素时，就会使用它。

**参数**
+ `field.$[]`: 带有 all 位置运算符的数组字段，用于更新所有元素。

## 示例（MongoDB 外壳）
<a name="dollarBrackets-update-examples"></a>

以下示例演示如何使用`$[]`运算符更新所有数组元素。

**创建示例文档**

```
db.products.insertOne({
  _id: 1,
  name: "Laptop",
  prices: [1000, 1100, 1200]
});
```

**查询示例**

```
db.products.updateOne(
  { _id: 1 },
  { $inc: { "prices.$[]": 50 } }
);
```

**输出**

```
{
  "_id" : 1,
  "name" : "Laptop",
  "prices" : [ 1050, 1150, 1250 ]
}
```

## 代码示例
<a name="dollarBrackets-update-code"></a>

要查看使用`$[]`运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

`$[<identifier>]`过滤后的位置运算符会更新所有符合指定过滤条件的数组元素。它与有选择地更新数组元素的`arrayFilters`选项一起使用。

**参数**
+ `field.$[identifier]`: 带有筛选位置运算符的数组字段。
+ `arrayFilters`：一组筛选条件，用于确定要更新的元素。

## 示例（MongoDB 外壳）
<a name="dollarIdentifier-update-examples"></a>

以下示例演示如何使用`$[<identifier>]`运算符根据条件更新特定的数组元素。

**创建示例文档**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  grades: [
    { subject: "Math", score: 85 },
    { subject: "Science", score: 92 },
    { subject: "History", score: 78 }
  ]
});
```

**查询示例**

```
db.students.updateOne(
  { _id: 1 },
  { $inc: { "grades.$[elem].score": 5 } },
  { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
);
```

**输出**

```
{
  "_id" : 1,
  "name" : "Alice",
  "grades" : [
    { "subject" : "Math", "score" : 90 },
    { "subject" : "Science", "score" : 97 },
    { "subject" : "History", "score" : 78 }
  ]
}
```

## 代码示例
<a name="dollarIdentifier-update-code"></a>

要查看使用`$[<identifier>]`运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

仅当数组中尚不存在值时，Amazon DocumentDB 中的`$addToSet`运算符才用于向该数组添加值。这对于确保数组包含唯一元素很有用。

**参数**
+ `field`：要更新的字段。
+ `value`：要添加到数组字段的值。这可以是单个值或表达式。

## 示例（MongoDB 外壳）
<a name="addToSet-examples"></a>

以下示例演示如何使用`$addToSet`运算符向数组添加唯一元素。

**创建示例文档**

```
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"] }
])
```

**查询示例**

```
db.products.update(
  { "item": "apple" },
  { $addToSet: { "tags": "green" } }
)
```

**输出**

```
{ "_id": 1, "item": "apple", "tags": ["fruit", "red", "round", "green"] }
```

在此示例中，`$addToSet`操作员将 “绿色” 标签添加到文档的 “标签” 数组中，其中 “项目” 字段为 “apple”。由于 “green” 不在数组中，因此已将其添加。

## 代码示例
<a name="addToSet-code"></a>

要查看使用该`$addToSet`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的运`$bit`算符允许您对给定字段的位执行按位运算。这对于设置、清除或检查数字中各个位的状态之类的任务很有用。

**参数**
+ `field`：要对其执行按位运算的字段。
+ `and`：用于对字段执行按位与运算的整数值。
+ `or`：用于对字段执行按位或运算的整数值。
+ `xor`：用于对字段执行按位异或运算的整数值。

## 示例（MongoDB 外壳）
<a name="bit-examples"></a>

以下示例演示如何使用`$bit`运算符对数值字段执行按位运算。

**创建示例文档**

```
db.numbers.insert([
  { "_id": 1, "number": 5 },
  { "_id": 2, "number": 12 }
])
```

**查询示例**

```
db.numbers.update(
  { "_id": 1 },
  { "$bit": { "number": { "and": 3 } } }
)
```

**输出**

```
{
  "_id": 1,
  "number": 1
}
```

在此示例中，`$bit`运算符用于对文档的 “数字” 字段执行按位与运算，其值为 1。`_id`结果是 “数字” 字段的值设置为 1，这是在原始值 5 和值 3 之间按位运算的结果。

## 代码示例
<a name="bit-code"></a>

要查看使用该`$bit`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

运`$currentDate`算符用于将字段的值设置为当前日期和时间。此运算符对于在插入或更新文档时使用当前时间戳自动更新字段很有用。

**参数**
+ `field`：要使用当前日期和时间更新的字段。
+ `type`:（可选）指定用于当前日期的 BSON 类型。可以是 `date` 或 `timestamp`。

## 示例（MongoDB 外壳）
<a name="currentDate-examples"></a>

以下示例演示如何使用`$currentDate`运算符将`lastModified`字段设置为插入新文档时的当前日期和时间。

**创建示例文档**

```
db.users.insert({
  name: "John Doe",
  email: "john.doe@example.com"
})
```

**查询示例**

```
db.users.updateOne(
  { name: "John Doe" },
  { $currentDate: { lastModified: true } }
)
```

**查看更新的文档**

```
db.users.findOne({ name: "John Doe" })
```

**输出**

```
{
  _id: ObjectId('...'),
  name: 'John Doe',
  email: 'john.doe@example.com',
  lastModified: ISODate('2025-10-25T22:50:29.963Z')
}
```

## 代码示例
<a name="currentDate-code"></a>

要查看使用该`$currentDate`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$each`运算符与其他更新运算符（例如`$push`和）结合使用`$addToSet`，向数组字段添加多个值。它允许在单个操作中向数组添加多个元素，而不必执行多个更新操作。

**参数**
+ `value`：要添加到数组字段的值数组。

## 示例（MongoDB 外壳）
<a name="each-examples"></a>

以下示例演示如何使用带有`$each`运算符的`$push`运算符将多个元素添加到数组字段中。

**创建示例文档**

```
db.fruits.insertOne({
  _id: 1,
  fruits: ["apple", "banana"]
})
```

**查询示例**

```
db.fruits.updateOne(
  { _id: 1 },
  { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
)
```

**查看更新的文档**

```
db.fruits.findOne({ _id: 1 })
```

**输出**

```
{
  _id: 1,
  fruits: [ 'apple', 'banana', 'cherry', 'durian', 'elderberry' ]
}
```

## 代码示例
<a name="each-code"></a>

要查看使用该`$each`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$inc`运算符用于将字段的值增加指定量。它用于更新数值字段，例如计数器或评级，而无需检索当前值、计算新值然后更新该字段。

**参数**
+ `field`：要递增的字段的名称。
+ `amount`：该字段的增量值。这可以是正值或负值。

## 示例（MongoDB 外壳）
<a name="inc-examples"></a>

以下示例演示如何使用`$inc`运算符来增加文档的`age`字段。

**创建示例文档**

```
db.users.insertOne({_id: 123, name: "John Doe", age: 30})
```

**查询示例**

```
db.users.updateOne({_id: 123}, {$inc: {age: 1}})
```

**查看更新的文档**

```
db.users.findOne({_id: 123})
```

**输出**

```
{ "_id" : 123, "name" : "John Doe", "age" : 31 }
```

## 代码示例
<a name="inc-code"></a>

要查看使用该`$inc`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

只有当指定值大于当前字段值时，`$max`更新运算符才会更新字段的值。此运算符对于在更新期间保持最大值很有用。

**参数**
+ `field`：要更新的字段。
+ `value`：要与当前字段值进行比较的值。

## 示例（MongoDB 外壳）
<a name="max-update-examples"></a>

以下示例演示如何使用`$max`运算符更新玩家记录的最高分数。

**创建示例文档**

```
db.scores.insertMany([
  { _id: 1, player: "Alice", highScore: 85 },
  { _id: 2, player: "Bob", highScore: 92 },
  { _id: 3, player: "Charlie", highScore: 78 }
])
```

**更新示例**

```
db.scores.updateOne(
  { _id: 1 },
  { $max: { highScore: 95 } }
)
```

**结果**

Alice 的`highScore`字段更新为 95，因为 95 大于当前值 85。

```
{ "_id": 1, "player": "Alice", "highScore": 95 }
```

## 代码示例
<a name="max-update-code"></a>

要查看使用该`$max`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

只有当指定值小于当前字段值时，`$min`更新运算符才会更新字段的值。此运算符对于在更新期间保持最小值很有用。

**参数**
+ `field`：要更新的字段。
+ `value`：要与当前字段值进行比较的值。

## 示例（MongoDB 外壳）
<a name="min-update-examples"></a>

以下示例演示如何使用`$min`操作员更新气象站记录的最低温度。

**创建示例文档**

```
db.weather.insertMany([
  { _id: 1, station: "Station A", lowestTemp: 15 },
  { _id: 2, station: "Station B", lowestTemp: 20 },
  { _id: 3, station: "Station C", lowestTemp: 18 }
])
```

**更新示例**

```
db.weather.updateOne(
  { _id: 1 },
  { $min: { lowestTemp: 12 } }
)
```

**结果**

站点 A 的`lowestTemp`字段更新为 12，因为 12 小于当前值 15。

```
{ "_id": 1, "station": "Station A", "lowestTemp": 12 }
```

## 代码示例
<a name="min-update-code"></a>

要查看使用该`$min`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$mul`运算符用于将字段的值乘以指定的数字。这对于自动一致地更新多个文档非常有用，例如根据信用卡状态更新飞行里程。

**参数**
+ `field`：要相乘的字段。
+ `multiplier`：字段值乘以的数字。

## 示例（MongoDB 外壳）
<a name="mul-examples"></a>

此示例演示如何使用`$mul`运算符将该`credit_card`字段所在的所有文档的`flight_miles`值加倍`true`。

**创建示例文档**

```
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] }
]);
```

**查询示例**

```
db.miles.update(
  { "credit_card": { "$eq": true } },
  { "$mul": { "flight_miles.$[]": NumberInt(2) } },
  { "multi": true }
);
```

**输出**

```
{ "_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 ] }
```

对于持有信用卡的乘客，他们的飞行里程翻了一番。

`$[]`位置数组运算符用于将`$mul`运算应用于`flight_miles`数组中的每个元素。

## 代码示例
<a name="mul-code"></a>

要查看使用该`$mul`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$pop`运算符用于从数组字段中删除第一个或最后一个元素。当您需要维护固定大小的数组或在文档中实现类似队列的数据结构时，它特别有用。

**参数**
+ `field`: 要从中移除元素的数组字段的名称。
+ `value`：一个整数值，用于确定要移除的元素的位置。值为`1`移除最后一个元素，而值为`-1`移除第一个元素。

## 示例（MongoDB 外壳）
<a name="pop-examples"></a>

此示例演示如何使用`$pop`运算符从数组字段中删除第一个和最后一个元素。

**创建示例文档**

```
db.users.insertMany([
  { "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming", "hiking"] },
  { "_id": 2, "name": "Jane Smith", "hobbies": ["cooking", "gardening", "painting"] }
])
```

**查询示例**

```
// 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 } })
```

**输出**

```
{ "_id" : 1, "name" : "John Doe", "hobbies" : [ "swimming", "hiking" ] }
{ "_id" : 2, "name" : "Jane Smith", "hobbies" : [ "cooking", "gardening" ] }
```

## 代码示例
<a name="pop-code"></a>

要查看使用该`$pop`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$position`修饰符指定`$push`运算符在数组中插入元素的位置。如果不使用`$position`修饰`$push`符，则运算符将元素插入数组的末尾。

**参数**
+ `field`：要更新的数组字段。
+ `num`: 数组中应插入元素的位置，基于从零开始的索引。

**注意**：要使用`$position`修饰符，它必须与修`$each`饰符一起出现。

## 示例（MongoDB 外壳）
<a name="position-examples"></a>

以下示例演示如何使用`$position`操作员在项目管理系统的特定位置插入任务。

**创建示例文档**

```
db.projects.insertOne({ "_id": 1, "name": "Website Redesign", "tasks": ["Design mockups"] })
```

**查询示例 1-在开头添加紧急任务**

```
db.projects.updateOne(
   { _id: 1 },
   {
     $push: {
        tasks: {
           $each: ["Security audit", "Performance review"],
           $position: 0
        }
     }
   }
)
```

**输出 1**

```
{ "_id": 1, "name": "Website Redesign", "tasks": ["Security audit", "Performance review", "Design mockups"] }
```

**查询示例 2-在特定位置添加任务**

```
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
        }
     }
   }
)
```

**输出 2**

```
{ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Code review", "Testing phase", "Deploy to store"] }
```

## 代码示例
<a name="position-code"></a>

要查看使用该`$position`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

该`$pull`运算符用于从数组中删除一个或多个与指定条件匹配的值的所有实例。当您需要从文档中的数组字段中删除特定元素时，此运算符很有用。

**参数**
+ `field`：要从中删除值的数组字段的名称。
+ `value`：决定要从数组中删除哪些元素的值或条件。

## 示例（MongoDB 外壳）
<a name="pull-examples"></a>

以下示例演示如何使用`$pull`运算符从数组字段中移除元素。

**创建示例文档**

```
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"]
  }
])
```

**查询示例**

```
db.restaurants.updateMany(
  { cuisine: "Italian" },
  { $pull: { features: "Takeout" } }
)
```

**输出**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

上面的查询从所有`cuisine`字段为 “意大利语” 的文档中删除 “Takeout” 功能。

## 代码示例
<a name="pull-code"></a>

要查看使用该`$pull`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$pullAll`运算符用于从数组字段中删除指定值的所有实例。当你需要在一次操作中从数组中移除多个元素时，这特别有用。

**参数**
+ `field`：要从中移除元素的数组字段的名称。
+ `value`：要从数组字段中移除的值数组。

## 示例（MongoDB 外壳）
<a name="pullAll-examples"></a>

以下示例演示如何使用`$pullAll`运算符从数组字段中移除多个元素。

**创建示例文档**

```
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"]
  }
])
```

**查询示例**

```
db.restaurants.update(
  { "name": "Taj Mahal" },
  { $pullAll: { "features": ["Private Dining", "Live Music"] } }
)
```

**输出**

```
{
  "name": "Taj Mahal",
  "cuisine": "Indian",
  "features": []
}
```

## 代码示例
<a name="pullAll-code"></a>

要查看使用该`$pullAll`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$push`运算符用于向文档的数组字段中添加项目。当您需要在不覆盖整个数组的情况下向现有数组追加新数据时，此运算符特别有用。

**参数**
+ `field`: 应向其添加新元素的数组字段的名称。
+ `value`：要添加到数组中的值。
+ `position`:（可选）一个修饰符，用于指定应在数组中添加新元素的位置。支持的修饰符包括`$`（添加到数组末尾）和`$[]`（添加到数组末尾，忽略任何数组过滤器）。

## 示例（MongoDB 外壳）
<a name="push-examples"></a>

以下示例演示如何使用`$push`运算符向文档中的数组字段添加新元素。

**创建示例文档**

```
db.users.insert([
  { _id: 1, name: "John Doe", hobbies: ["reading", "swimming"] },
  { _id: 2, name: "Jane Smith", hobbies: ["gardening", "cooking"] }
])
```

**查询示例**

```
db.users.updateOne(
  { _id: 1 },
  { $push: { hobbies: "hiking" } }
)
```

**输出**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

运行更新后，带有的文档的`hobbies`数组`_id: 1`将更新为`[&quot;reading&quot;, &quot;swimming&quot;, &quot;hiking&quot;]`。

## 代码示例
<a name="push-code"></a>

要查看使用该`$push`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$rename`运算符用于重命名文档中的字段。当您需要更新文档结构或将其与新的数据模型对齐时，此运算符可能特别有用。

**参数**
+ `field`：要重命名的字段。
+ `newName`：该字段的新名称。

## 示例（MongoDB 外壳）
<a name="rename-examples"></a>

以下示例演示如何使用`$rename`运算符在`&quot;Date.DoW&quot;`字段设置为的文档`&quot;Date.DayOfWeek&quot;`中将该`&quot;DocName&quot;`字段重命名为`&quot;Document 1&quot;`。

**创建示例文档**

```
db.example.insertOne({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**查询示例**

```
db.example.update(
    { "DocName": "Document 1" },
    { $rename: { "Date.DoW": "Date.DayOfWeek" } }
)
```

**输出**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DayOfWeek": "Saturday"
    },
    "Words": 2482
}
```

## 代码示例
<a name="rename-code"></a>

要查看使用该`$rename`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$set`运算符用于更新文档中指定字段的值。此运算符允许您在文档中添加新字段或修改现有字段。它是 MongoDB Java 驱动程序中的基本更新操作符，与亚马逊 DocumentDB 兼容。

**参数**
+ `field`：要更新的字段。
+ `value`：该字段的新值。

## 示例（MongoDB 外壳）
<a name="set-examples"></a>

以下示例演示如何使用`$set`运算符更新文档中的`Item`字段。

**创建示例文档**

```
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
    }
  }
])
```

**查询示例**

```
db.example.update(
  { "Item": "Pen" },
  { $set: { "Item": "Gel Pen" } }
)
```

**输出**

```
{
  "Item": "Gel Pen",
  "Colors": ["Red", "Green", "Blue", "Black"],
  "Inventory": {
    "OnHand": 244,
    "MinOnHand": 72
  }
}
```

## 代码示例
<a name="set-code"></a>

要查看使用该`$set`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

如果要插入文档，Amazon DocumentDB 中的`$setOnInsert`运算符用于设置字段的值，但是如果要更新文档，则该运算符无效。

**参数**
+ `field`：要设置的字段。
+ `value`：要分配给该字段的值。

## 示例（MongoDB 外壳）
<a name="setOnInsert-examples"></a>

以下示例演示了`$setOnInsert`运算符在 Amazon DocumentDB 中的用法。如果文档尚不存在，则它会创建一个新文档，但是如果正在更新该文档，则不起作用。

**创建示例文档**

```
db.users.insertOne({
  _id: 1,
  name: "John Doe",
  age: 30
})
```

**查询示例 1-更新现有文档**

```
db.users.update(
  { _id: 1 },
  {
    $set: { age: 31 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**输出 1**

```
{
  _id: 1,
  name: "John Doe",
  age: 31
}
```

输出显示文档已更新，但由于文档已经存在，因此**未添加**该`createdAt`字段。该`$setOnInsert`运算符仅在插入新文档时适用。

**查询示例 2-插入新文档（upsert）**

```
db.users.update(
  { _id: 2 },
  {
    $set: { name: "Jane Smith", age: 25 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**输出 2**

```
{
  _id: 2,
  name: "Jane Smith", 
  age: 25,
  createdAt: ISODate("2025-10-31T09:57:52.459Z")
}
}
```

## 代码示例
<a name="setOnInsert-code"></a>

要查看使用该`$setOnInsert`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

u `$slice` pdate 运算符通过限制数组的大小来修改数组。与`$push`运算符一起使用时，它会限制数组中元素的数量，只保留指定数量的最新或最旧的元素。

**参数**
+ `field`：要修改的数组字段。
+ `count`：要保留的最大元素数。正值保留前 N 个元素，负值保留最后 N 个元素。

## 示例（MongoDB 外壳）
<a name="slice-update-examples"></a>

以下示例演示如何使用`$slice`更新运算符`$push`来维护固定大小的近期分数组。

**创建示例文档**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  scores: [85, 90, 78]
});
```

**查询示例**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      scores: {
        $each: [92, 88],
        $slice: -3
      }
    }
  }
)
```

**输出**

```
{
  "_id" : 1,
  "name" : "Alice",
  "scores" : [ 78, 92, 88 ]
}
```

在此示例中，`$slice: -3`修饰符在将新值推送到数组后仅保留最后三个元素。

## 代码示例
<a name="slice-update-code"></a>

要查看使用`$slice`更新运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

与运算符一起使用时，u `$sort` pdate 修饰`$push`符会对数组元素进行排序。它根据指定的字段值或元素本身按升序或降序排列数组元素。

**参数**
+ `field`：要修改的数组字段。
+ `order`：`1`用于升序或`-1`降序。

## 示例（MongoDB 外壳）
<a name="sort-update-examples"></a>

以下示例演示了使用`$sort`修饰符wit `$push` h来添加新的测验分数并按降序对它们进行排序。

**创建示例文档**

```
db.students.insertOne({
  _id: 1,
  name: "Bob",
  quizzes: [
    { score: 85, date: "2024-01-15" },
    { score: 92, date: "2024-02-10" }
  ]
});
```

**查询示例**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      quizzes: {
        $each: [{ score: 78, date: "2024-03-05" }],
        $sort: { score: -1 }
      }
    }
  }
)
```

**输出**

```
{
  "_id" : 1,
  "name" : "Bob",
  "quizzes" : [
    { "score" : 92, "date" : "2024-02-10" },
    { "score" : 85, "date" : "2024-01-15" },
    { "score" : 78, "date" : "2024-03-05" }
  ]
}
```

## 代码示例
<a name="sort-update-code"></a>

要查看使用`$sort`更新修饰符的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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>

Amazon DocumentDB 中的`$unset`运算符用于从文档中删除指定字段。使用删除字段时`$unset`，该字段将从文档中删除，并相应地减小文档的大小。当你想从文档中删除不必要的数据时，这可能很有用。

**参数**
+ `field`：要从文档中移除的字段。这可以是单个字段，也可以是嵌套字段的虚线路径。

## 示例（MongoDB 外壳）
<a name="unset-examples"></a>

以下示例演示如何使用`$unset`运算符从`example`集合中的文档中移除该`Words`字段。

**创建示例文档**

```
db.example.insert({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**查询示例**

```
db.example.update(
    { "DocName" : "Document 1" },
    { $unset: { Words:1 } }
)
```

**输出**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    }
}
```

在此示例中，`$unset`运算符用于从文档中移除`DocName`等于 “文档 1” 的`Words`字段。生成的文档不再包含该`Words`字段。

## 代码示例
<a name="unset-code"></a>

要查看使用该`$unset`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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()
```

------