

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon DocumentDB 中支援的 MongoDB APIs、操作和資料類型
<a name="mongo-apis"></a>

Amazon DocumentDB （與 MongoDB 相容） 是一種快速、可擴展、高可用性且全受管的文件資料庫服務，可支援 MongoDB 工作負載。Amazon DocumentDB 與 MongoDB 3.6、4.0、5.0 和 8.0 APIs。本區段列出支援的功能。如需使用 MongoDB APIs和驅動程式的支援，請參閱 MongoDB 社群論壇。如需使用 Amazon DocumentDB 服務的支援，請聯絡適當的 AWS 支援團隊。如需 Amazon DocumentDB 和 MongoDB 之間的功能差異，請參閱 [功能差異：Amazon DocumentDB 和 MongoDB](functional-differences.md)。

不支援 MongoDB 命令和運算子，這些命令僅供內部使用或不適用於全受管服務，且未包含在支援的功能清單中。

自推出以來，我們已新增超過 50 項額外功能，並會繼續向客戶提供他們所需的功能。如需最新啟動的資訊，請參閱 [Amazon DocumentDB 公告](https://aws.amazon.com/documentdb/resources/)。

如果您有不支援我們建置的功能，請使用您的 accountID、請求的功能和使用案例傳送給 [Amazon DocumentDB 服務團隊](mailto:documentdb-feature-request@amazon.com)，讓我們知道。
+ [資料庫命令](#mongo-apis-database)
+ [查詢和投影運算子](#mongo-apis-query)
+ [更新運算子](#mongo-apis-update)
+ [Geospatial (地理空間)](#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)
+ [使用者管理](#mongo-apis-dababase-user-management)
+ [碎片命令](#mongo-apis-dababase-sharding)

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


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 彈性叢集 | 
| --- | --- | --- | --- | --- | --- | 
|  Capped Collections  |  否  |  否  |  否  |  否  |  否  | 
|  cloneCollectionAsCapped  |  否  |  否  |  否  |  否  |  否  | 
|  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  |  是  |  是  |  是  |  是  |  是  | 
|  distinct  |  是  |  是  |  是  |  是  |  是  | 
|  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  |  是  |  是  |  是  |  是  |  是  | 
|  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 | 彈性叢集 | 
| --- | --- | --- | --- | --- | --- | 
|  Change streams  |  [是](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)  |  否  | 
|  delete  |  是  |  是  |  是  |  是  |  是  | 
|  find  |  是  |  是  |  是  |  是  |  是  | 
|  findAndModify  |  是  |  是  |  是  |  是  |  是  | 
|  getLastError  |  否  |  否  |  否  |  否  |  否  | 
|  getMore  |  是  |  是  |  是  |  是  |  是  | 
|  getPrevError  |  否  |  否  |  否  |  否  |  否  | 
|  GridFS  |  是  |  是  |  是  |  是  |  否  | 
|  insert  |  是  |  是  |  是  |  是  |  是  | 
|  parallelCollectionScan  |  否  |  否  |  否  |  否  |  否  | 
|  resetError  |  否  |  否  |  否  |  否  |  否  | 
|  update  |  是  |  是  |  是  |  是  |  是  | 
|  ReplaceOne  |  是  |  是  |  是  |  是  |  是  | 

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


| 命令 | 3.6 | 4.0 | 5.0 | 8.0 | 彈性叢集 | 
| --- | --- | --- | --- | --- | --- | 
|  createRole  |  是  |  是  |  是  |  是  |  否  | 
|  dropAllRolesFromDatabase  |  是  |  是  |  是  |  是  |  否  | 
|  dropRole  |  是  |  是  |  是  |  是  |  否  | 
|  grantRolesToRole  |  是  |  是  |  是  |  是  |  否  | 
|  revokeRolesFromRole  |  是  |  是  |  是  |  是  |  否  | 
|  revokePrivilegesFromRole  |  是  |  是  |  是  |  是  |  否  | 
|  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  |  否  |  是  |  是  |  是  |  否  | 

### 使用者管理
<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  |  否  | 
|  addShardToZone  |  否  | 
|  balancerCollectionStatus  |  否  | 
|  balancerStart  |  否  | 
|  balancerStatus  |  否  | 
|  balancerStop  |  否  | 
|  checkShardingIndex  |  否  | 
|  clearJumboFlag  |  否  | 
|  cleanupOrphaned  |  否  | 
|  cleanupReshardCollection  |  否  | 
|  commitReshardCollection  |  否  | 
|  enableSharding  |  是  | 
|  flushRouterConfig  |  否  | 
|  getShardMap  |  否  | 
|  getShardVersion  |  否  | 
|  isdbgrid  |  否  | 
|  listShards  |  否  | 
|  medianKey  |  否  | 
|  moveChunk  |  否  | 
|  movePrimary  |  否  | 
|  mergeChunks  |  否  | 
|  refineCollectionShardKey  |  否  | 
|  removeShard  |  否  | 
|  removeShardFromZone  |  否  | 
|  reshardCollection  |  否  | 
|  setAllowMigrations  |  否  | 
|  setShardVersion  |  否  | 
|  shardCollection  |  是  | 
|  shardingState  |  否  | 
|  分割  |  否  | 
|  splitVector  |  否  | 
|  unsetSharding  |  否  | 
|  updateZoneKeyRange  |  否  | 

## 查詢和投影運算子
<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)  |  是  |  是  |  是  |  是  |  是  | 

## Geospatial (地理空間)
<a name="mongo-apis-geospatial"></a>

### 幾何指標
<a name="mongo-apis-geospatial-geometry-specifiers"></a>


| 查詢選取器 | 3.6 | 4.0 | 5.0 | 8.0 | 彈性叢集 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1box  |  否  |  否  |  否  |  否  |  否  | 
|  \$1center  |  否  |  否  |  否  |  否  |  否  | 
|  \$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()  |  是  |  是  |  是  |  是  |  是  | 
|  cursor.noCursorTimeout()  |  否  |  否  |  否  |  否  |  否  | 
|  cursor.objsLeftInBatch()  |  是  |  是  |  是  |  是  |  否  | 
|  cursor.pretty()  |  是  |  是  |  是  |  是  |  否  | 
|  cursor.readConcern()  |  是  |  是  |  是  |  是  |  否  | 
|  cursor.readPref()  |  是  |  是  |  是  |  是  |  否  | 
|  cursor.returnKey()  |  否  |  否  |  否  |  否  |  否  | 
|  cursor.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>


| 表達式 | 3.6 | 4.0 | 5.0 | 8.0 | 彈性叢集 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1累積器  |  -  |  -  |  否  |  否  |  否  | 
|  [\$1addToSet](addToSet-aggregation.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1avg](avg.md)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1count](count.md)  |  -  |  -  |  否  |  否  |  否  | 
|  \$1covariancePop  |  否  |  否  |  否  |  否  |  否  | 
|  \$1covarianceSamp  |  否  |  否  |  否  |  否  |  否  | 
|  \$1denseRank  |  否  |  否  |  否  |  否  |  否  | 
|  \$1衍生性  |  否  |  否  |  否  |  否  |  否  | 
|  \$1documentNumber  |  否  |  否  |  否  |  否  |  否  | 
|  \$1expMovingAvg  |  否  |  否  |  否  |  否  |  否  | 
|  [\$1first](first.md)  |  是  |  是  |  是  |  是  |  是  | 
|  \$1整合  |  否  |  否  |  否  |  否  |  否  | 
|  [\$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)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1isoDayOfWeek](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 | 彈性叢集 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1自然](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)  |  是  |  是  |  是  |  是  |  是  | 
|  [\$1merge](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)  |  否  |  否  |  否  |  是  |  否  | 
|  [\$1vectorSearch](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 | 彈性叢集 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1轉換](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 位元整數  (int)  |  是  |  是  |  是  |  是  |  是  | 
|  64 位元整數  （長）  |  是  |  是  |  是  |  是  |  是  | 
|  陣列  |  是  |  是  |  是  |  是  |  是  | 
|  二進位資料  |  是  |  是  |  是  |  是  |  是  | 
|  Boolean  |  是  |  是  |  是  |  是  |  是  | 
|  Date  |  是  |  是  |  是  |  是  |  是  | 
|  DBPointer  |  否  |  否  |  否  |  否  |  否  | 
|  DBRefs  |  否  |  否  |  否  |  否  |  否  | 
|  Decimal128  |  是  |  是  |  是  |  是  |  是  | 
|  Double  |  是  |  是  |  是  |  是  |  是  | 
|  JavaScript  |  否  |  否  |  否  |  否  |  否  | 
|  JavaScript （含 範圍）  |  否  |  否  |  否  |  否  |  否  | 
|  MaxKey  |  是  |  是  |  是  |  是  |  是  | 
|  MinKey  |  是  |  是  |  是  |  是  |  是  | 
|  Null  |  是  |  是  |  是  |  是  |  是  | 
|  物件  |  是  |  是  |  是  |  是  |  是  | 
|  ObjectId  |  是  |  是  |  是  |  是  |  是  | 
|  Regular expression (常規表達式)  |  是  |  是  |  是  |  是  |  是  | 
|  String  |  是  |  是  |  是  |  是  |  是  | 
|  Symbol  |  否  |  否  |  否  |  否  |  否  | 
|  時間戳記  |  是  |  是  |  是  |  是  |  是  | 
|  未定義  |  否  |  否  |  否  |  否  |  否  | 

## 索引和索引屬性
<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 | 彈性叢集 | 
| --- | --- | --- | --- | --- | --- | 
|  背景介紹  |  是  |  是  |  是  |  是  |  是  | 
|  不區分大小寫  |  否  |  否  |  否  |  是  |  否  | 
|  Hidden  |  否  |  否  |  否  |  否  |  否  | 
|  部分  |  否  |  否  |  是  |  是  |  否  | 
|  稀疏  |  是  |  是  |  是  |  是  |  是  | 
|  文字  |  否  |  否  |  是  |  是  |  否  | 
|  TTL  |  是  |  是  |  是  |  是  |  是  | 
|  唯一  |  是  |  是  |  是  |  是  |  是  | 
|  向量  |  否  |  否  |  是  |  是  |  否  | 

如需特定 MongoDB 運算子的詳細資訊，請參閱下列主題：
+ [彙總管道運算子](mongo-apis-aggregation-pipeline-operators.md)
+ [Geospatial (地理空間)](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)
+ [\$1轉換](convert.md)
+ [\$1count](count.md)
+ [\$1currentOp](currentOp.md)
+ [\$1dateAdd](dateAdd.md)
+ [\$1dateDiff](dateDiff.md)
+ [\$1dateFromString](dateFromString.md)
+ [\$1dateSubtract](dateSubtract.md)
+ [\$1dateToString](dateToString.md)
+ [\$1dateTrunc](dateTrunc.md)
+ [\$1dayOfMonth](dayOfMonth.md)
+ [\$1dayOfWeek](dayOfWeek.md)
+ [\$1dayOfYear](dayOfYear.md)
+ [\$1divide](divide.md)
+ [\$1eq](eq-aggregation.md)
+ [\$1exp](exp.md)
+ [\$1filter](filter.md)
+ [\$1first](first.md)
+ [\$1floor](floor.md)
+ [\$1geoNear](geoNear.md)
+ [\$1group](group.md)
+ [\$1gt](gt-aggregation.md)
+ [\$1gte](gte-aggregation.md)
+ [\$1hour](hour.md)
+ [\$1ifNull](ifNull.md)
+ [\$1in](in-aggregation.md)
+ [\$1indexOfArray](indexOfArray.md)
+ [\$1indexOfBytes](indexOfBytes.md)
+ [\$1indexOfCP](indexOfCP.md)
+ [\$1indexStats](indexStats.md)
+ [\$1isArray](isArray.md)
+ [\$1isoDayOfWeek](isoDayOfWeek.md)
+ [\$1isoWeek](isoWeek.md)
+ [\$1isoWeekYear](isoWeekYear.md)
+ [\$1last](last.md)
+ [\$1let](let.md)
+ [\$1limit](limit.md)
+ [\$1literal](literal.md)
+ [\$1ln](ln.md)
+ [\$1log](log.md)
+ [\$1log10](log10.md)
+ [\$1lt](lt-aggregation.md)
+ [\$1lte](lte-aggregation.md)
+ [\$1lookup](lookup.md)
+ [\$1ltrim](ltrim.md)
+ [\$1map](map.md)
+ [\$1match](match.md)
+ [\$1max](max.md)
+ [\$1meta](meta-aggregation.md)
+ [\$1merge](merge.md)
+ [\$1mergeObjects](mergeObjects.md)
+ [\$1millisecond](millisecond.md)
+ [\$1min](min.md)
+ [\$1minute](minute.md)
+ [\$1mod](mod.md)
+ [\$1month](month.md)
+ [\$1multiply](multiply.md)
+ [\$1自然](natural.md)
+ [\$1ne](ne-aggregation.md)
+ [\$1not](not-aggregation.md)
+ [\$1objectToArray](objectToArray.md)
+ [\$1or](or-aggregation.md)
+ [\$1out](out.md)
+ [\$1pow](pow.md)
+ [\$1push](push-aggregation.md)
+ [\$1project](project.md)
+ [\$1rand](rand.md)
+ [\$1range](range.md)
+ [\$1redact](redact.md)
+ [\$1reduce](reduce.md)
+ [\$1regexFind](regexFind.md)
+ [\$1regexFindAll](regexFindAll.md)
+ [\$1regexMatch](regexMatch.md)
+ [\$1replaceAll](replaceAll.md)
+ [\$1replaceOne](replaceOne.md)
+ [\$1replaceRoot](replaceRoot.md)
+ [\$1replaceWith](replaceWith.md)
+ [\$1reverseArray](reverseArray.md)
+ [\$1rtrim](rtrim.md)
+ [\$1sample](sample.md)
+ [\$1search](search.md)
+ [\$1second](second.md)
+ [\$1set](set-stage.md)
+ [\$1setDifference](setDifference.md)
+ [\$1setEquals](setEquals.md)
+ [\$1setIntersection](setIntersection.md)
+ [\$1setIsSubset](setIsSubset.md)
+ [\$1setUnion](setUnion.md)
+ [\$1skip](skip.md)
+ [\$1slice](slice.md)
+ [\$1size](size.md)
+ [\$1sort](sort.md)
+ [\$1split](split.md)
+ [\$1sqrt](sqrt.md)
+ [\$1strLenBytes](strLenBytes.md)
+ [\$1strLenCP](strLenCP.md)
+ [\$1strcasecmp](strcasecmp.md)
+ [\$1substr](substr.md)
+ [\$1substrBytes](substrBytes.md)
+ [\$1substrCP](substrCP.md)
+ [\$1subtract](subtract.md)
+ [\$1sum](sum.md)
+ [\$1switch](switch.md)
+ [\$1toBool](toBool.md)
+ [\$1toDate](toDate.md)
+ [\$1toDecimal](toDecimal.md)
+ [\$1toDouble](toDouble.md)
+ [\$1toInt](toInt.md)
+ [\$1toLong](toLong.md)
+ [\$1toLower](toLower.md)
+ [\$1toObjectId](toObjectId.md)
+ [\$1toString](toString.md)
+ [\$1toUpper](toUpper.md)
+ [\$1trim](trim.md)
+ [\$1type](type-aggregation.md)
+ [\$1unset](unset-stage.md)
+ [\$1unwind](unwind.md)
+ [\$1vectorSearch](vectorSearch.md)
+ [\$1week](week.md)
+ [\$1year](year.md)
+ [\$1zip](zip.md)

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

Amazon DocumentDB 中的`$$DESCEND`運算子是在`$redact`管道階段中使用的特殊位置陣列運算子。它會指示彙總管道遞減至目前的文件並處理所有欄位，無論其巢狀層級為何。

當`$redact`階段遇到`$$DESCEND`運算子時，它會讓目前文件中的所有欄位保持可見，並進一步處理它們。當您想要根據條件選擇性地修訂或剪除特定欄位，同時保留文件的結構時，這非常有用。

**參數**

無.

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

在此範例中，我們將使用 `$redact`階段搭配 `$$DESCEND`運算子，選擇性地顯示 `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 Shell)
<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 Shell)
<a name="PRUNE-examples"></a>

下列範例示範如何使用 `$$PRUNE`搭配 `$redact`，從結果中排除超過 30 年的使用者。

**建立範例文件**

```
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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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` 運算子用於檢查陣列中的所有元素是否評估為 true 值。

**參數**
+ `expression`：評估 陣列的表達式。

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

下列範例示範使用 `$allElementsTrue`來檢查陣列中的所有元素是否為 true。

**建立範例文件**

```
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 Shell)
<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` 運算子用於判斷陣列中的任何元素是否為 true。

**參數**
+ `field`：要評估的陣列欄位。

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

下列範例示範如何使用 `$anyElementTrue` 來檢查陣列中的任何元素是否為 true。

**建立範例文件**

```
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 Shell)
<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 Shell)
<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 Shell)
<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 版的新功能

Elastic 叢集不支援。

Amazon DocumentDB `$bucket` 中的彙總階段可讓您根據指定的表達式和儲存貯體邊界，將輸入文件分組至儲存貯體。這對於分析屬於特定值範圍或類別的資料非常有用。

**參數**
+ `groupBy` （必要）：指定要分組之值的表達式。
+ `boundaries` （必要）：定義儲存貯體邊界的雙值陣列。文件會根據落在指定邊界內的`groupBy`表達式值指派給儲存貯體。
+ `default` （選用）：為`groupBy`表達式值未落在任何指定邊界的文件輸出的常值。
+ `output` （選用）：指定要為每個儲存貯體輸出資訊的物件。您可以使用累積器運算子，例如 `$sum`、`$min`、 `$avg`和 `$max`來計算每個儲存貯體的彙總。

## 範例 (MongoDB Shell)
<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 版的新功能

Amazon DocumentDB 中的`$ceil`運算子與 MongoDB 一樣， 會將數字四捨五入到最接近的整數。當您需要對數值欄位執行數學操作，並確保結果是整數時，這會很有用。

**參數**
+ `expression`：要四捨五入的數值表達式。

## 範例 (MongoDB Shell)
<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>

Elastic 叢集不支援。

`$changeStream` 彙總階段會開啟變更串流游標，以監控集合的即時變更。當發生插入、更新、取代或刪除操作時，它會傳回變更事件文件。

**參數**
+ `fullDocument`：指定是否要傳回更新操作的完整文件。選項為 `default` 或 `updateLookup`。
+ `resumeAfter`：選用。繼續字符，從變更串流中的特定點繼續。
+ `startAtOperationTime`：選用。開始變更串流的時間戳記。
+ `allChangesForCluster`：選用。布林值。當 時`true`， 會監控叢集的所有變更 （適用於管理員資料庫）。當 `false`（預設） 時， 只會監看指定的集合。

## 範例 (MongoDB Shell)
<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 Shell)
<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 ]

以下是在 Node.js 應用程式中搭配`mongodb`驅動程式使用 `$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 ]

以下是在 Python 應用程式中搭配`pymongo`驅動程式使用 `$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 shell 中的 `db.collection.stats()`命令。此階段可用來擷取集合的相關資訊，例如文件數量、集合的總大小，以及各種效能指標。

**參數**
+ `latencyStats`：（選用） 指定收集延遲統計資料選項的文件。Amazon DocumentDB 不支援此參數。
+ `recordStats`：（選用） 指定收集記錄統計資料選項的文件。Amazon DocumentDB 不支援此參數。
+ `queryExecStats`：（選用） 指定收集查詢執行統計資料選項的文件。Amazon DocumentDB 不支援此參數。

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

下列範例示範如何使用彙總階段來擷取`db`資料庫中名為 `$collStats` 之集合`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 `$collStats` 驅動程式在 Node.js 應用程式中使用彙總階段的範例：

```
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 `$collStats` 驅動程式在 Python 應用程式中使用彙總階段的範例：

```
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 Shell)
<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 Shell)
<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`：如果表達式為 true，則傳回的`if`表達式。
+ `else`：如果表達式為 false，則傳回的`if`表達式。

## 範例 (MongoDB Shell)
<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()
```

------

# \$1轉換
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 版的新功能

Elastic 叢集不支援。

`$dateDiff` 彙總運算子會以指定的單位計算兩個日期之間的差異。它會傳回開始和結束日期之間跨越的單位邊界數目。

**參數**
+ `startDate`：開始日期表達式。
+ `endDate`：結束日期表達式。
+ `unit`：差異的時間單位。支援的單位為 `year`、`quarter`、`month`、`week`、`day`、`hour``minute`、、 `second`和 `millisecond`。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 版的新功能

Elastic 叢集不支援。

Amazon DocumentDB `$dateTrunc` 中的彙總運算子會將日期截斷為指定的單位。

**參數**
+ `date`：解析為日期或時間戳記的日期表達式。
+ `unit`：指定子trahend 表達式時間單位的字串。支援的單位為 `year`、`quarter`、`month`、`week`、`day`、`hour``minute`、、 `second`和 `millisecond`。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<a name="filter-examples"></a>

下列範例示範如何使用 `$filter`運算子來投影每個訂單的客戶，並建立新的陣列欄位 paidItems，只包含價格大於 15 的項目陣列中的項目。基本上，它會篩選每個訂單的項目，只包含成本超過 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 版的新功能。

Elastic 叢集不支援。

Amazon DocumentDB 中的`$first`運算子會從一組分組的文件中傳回第一個文件。它通常用於彙總管道，以擷取符合特定條件的第一個文件。

**參數**
+ `expression`：傳回為每個群組中第一個值的表達式。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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>

如果輸入表達式評估為 null 或未定義，則`$ifNull`運算子會用來傳回指定的值。此運算子在您想要提供預設值或處理 null/未定義案例的情況下非常有用。

**參數**
+ `expression`：要評估的表達式。
+ `replacement`：如果 `<expression>`評估為 null 或未定義，要傳回的值。

## 範例 (MongoDB Shell)
<a name="ifNull-examples"></a>

下列範例示範當 `name` 欄位為 null 或未定義時， `$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 Shell)
<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 Shell)
<a name="indexOfArray-examples"></a>

下列範例示範如何使用 \$1indexOfArray 運算子，在每個文件的「果」陣列中尋找元素「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 中的 \$1indexOfBytes 運算子用於根據字元的位元組位置，在字串中尋找子字串的起始索引。這在處理可能包含多位元組字元的文字資料時非常有用，例如在非 Latin 指令碼中找到的文字資料。

**參數**
+ `string`：要搜尋的輸入字串。
+ `substring`：要在輸入字串中搜尋的子字串。
+ `[<start>]`：（選用） 搜尋的開始位置 （以零為基礎）。如果未指定，搜尋會從字串開頭開始。

## 範例 (MongoDB Shell)
<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 Shell)
<a name="indexOfCP-examples"></a>

在此範例中，我們使用 `$indexOfCP`運算子在每個文件的桌面欄位中尋找第一個連字號字元的索引。

**建立範例文件**

```
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 Shell)
<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`運算子顯示`_id_`自上次重設或伺服器重新啟動後，索引已存取 5 次，且`product_1`索引已存取 10 次。

## 程式碼範例
<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 Shell)
<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()
```

------

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

Amazon DocumentDB 中的`$isoDayOfWeek`運算子會將日期的一週中的 ISO 日期傳回為整數值。ISO 週日期系統定義每週從星期一開始到星期日結束，第 1 週是包含當年第一個星期四的一週。

**參數**
+ `expression`：傳回一週中 ISO 日期的日期表達式。

## 範例 (MongoDB Shell)
<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 週日期系統是一年中週數的一種方式，其中新一年的第一週是包含該年第一個星期四的一週。這與 Gregorian 行事曆不同，新年的第一週是包含 1 月 1 日的一週。

**參數**

無

## 範例 (MongoDB Shell)
<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 週年編號與 Gregorian 曆年不同，因為該週年可能與曆年不同，尤其是在年初和年底。

**參數**
+ `expression`：傳回 ISO 8601 週年編號的日期表達式。

## 範例 (MongoDB Shell)
<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 Shell)
<a name="last-examples"></a>

下列範例示範使用 `$last`運算子搭配 `$filter`，從符合特定條件的陣列擷取最後一個元素 （例如，主體是 'science')。

**建立範例文件**

```
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 Shell)
<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`運算子用於限制查詢傳回的文件數量。它類似於 MongoDB `$limit`運算子，但在搭配 Amazon DocumentDB 使用它時有一些特定的考量。

在 Amazon DocumentDB 中，`$limit`運算子對於分頁很有用，您想要擷取相符文件總數的子集。它可讓您控制每個回應中傳回的文件數量，改善效能並減少透過網路傳輸的資料量。

**參數**
+ `limit`：要傳回的文件數量上限。這必須是非負整數值。

## 範例 (MongoDB Shell)
<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 Shell)
<a name="literal-examples"></a>

下列範例示範如何使用 `$literal`運算子在彙總管道中包含常值。`$literal` 運算子用於在 \$1gt 表達式中包含值 18 作為常值。這可讓彙總管道將年齡欄位與常值 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 Shell)
<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`運算子會計算數字的自然對數。它會傳回指定數字的 base-e 對數。

**參數**
+ `expression`：將計算自然對數的數字。
+ `base`：用於計算日誌的基本值。

## 範例 (MongoDB Shell)
<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`運算子用於計算數字的 base-10 對數。它適用於對彙總管道中的數值欄位執行對數計算。

**參數**
+ `expression`：計算 base-10 對數的數值表達式。

## 範例 (MongoDB Shell)
<a name="log10-examples"></a>

下列範例示範如何使用 `$log10`運算子來計算數值欄位的 base-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 Shell)
<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 Shell)
<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 Shell)
<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 版的新功能。

Elastic 叢集不支援。

Amazon DocumentDB 中的`$ltrim`運算子用於從字串中移除前置字元。根據預設，它會移除前導空格字元，但您也可以透過傳遞字元引數來指定要移除的一組字元。

**參數**
+ `input`：要從中移除前導空格字元的輸入字串。
+ `chars`：（選用） 移除特定字元。

## 範例 (MongoDB Shell)
<a name="ltrim-examples"></a>

下列範例示範 的使用方式`$ltrim`，以從字串開頭移除指定的字元 (" \$1")。

**建立範例文件**

```
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`：要套用至輸入陣列中每個元素的表達式。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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()
```

------

# \$1merge
<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`：（必要） 做為輸入文件與目標集合之間相符條件的欄位 (s)。
+ `whenMatched`：（選用） 當輸入文件符合目標集合中的現有文件時，要執行的動作。支援的值為：`"merge"`、`"replace"`、`"keepExisting"` 和 `"fail"`。
+ `whenNotMatched`：（選用） 當輸入文件不符合目標集合中的任何文件時，要執行的動作。支援的值為： `"insert"`和 `"fail"`。

## 範例 (MongoDB Shell)
<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 Operator 的範例：

```
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 Operator 的範例：

```
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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<a name="mod-examples"></a>

此範例示範如何在以 100 個套件運送時，使用 `$mod` 運算子來判斷剩餘小工具的數量。

**建立範例文件**

```
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 Shell)
<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 Shell)
<a name="multiply-examples"></a>

下列範例示範使用 `$multiply`來計算乘`bonus_miles`以 `base_miles`，以及`bonus_rate`針對使用信用卡進行旅程的客戶。

**文件範例**

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

------

# \$1自然
<a name="natural"></a>

Amazon DocumentDB 中的`$natural`運算子用於依其自然順序排序文件，這是它們插入集合的順序。這與預設排序行為相反，也就是根據指定欄位的值排序文件。

**參數**

無

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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>

彙總運算子會評估多個表達式，如果至少一個表達式評估為 `true`，則傳回 `$or` `true`。`false` 只有在所有表達式都是 時，才會傳回 `false`。

**參數**
+ `expressions`：要評估的表達式陣列。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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`：評估文件中`$$DESCEND`每個欄位 `$$KEEP`、 `$$PRUNE`或 的表達式。
+ `$$KEEP`：保留輸出文件中的目前欄位。
+ `$$PRUNE`：從輸出文件移除目前欄位。
+ `$$DESCEND`：遞迴地將`$redact`階段套用至目前欄位，也就是物件或陣列。

## 範例 (MongoDB Shell)
<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 Shell)
<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 版的新功能。

Elastic 叢集不支援。

Amazon DocumentDB 中的`$regexFind`運算子用於對文件中的字串欄位執行規則運算式比對。它可讓您搜尋和擷取符合指定規則表達式模式的特定子字串。

**參數**
+ `input`：要搜尋的字串欄位或表達式。
+ `regex`：要比對的規則表達式模式。
+ `options`：（選用） 指定規則表達式選用參數的物件，例如區分大小寫和多行比對。支援的選項為 `i`（不區分大小寫） 和 `m`（多行）。

## 範例 (MongoDB Shell)
<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 查詢規劃器文件】(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 Shell)
<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 查詢規劃器文件】(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 版的新功能。Elastic 叢集不支援。

Amazon DocumentDB 中的`$regexMatch`運算子用於對字串欄位執行規則運算式比對。它會傳回布林值 (`true` 或 `false`)，指出輸入字串是否符合指定的模式。

**參數**
+ `input`：針對規則表達式進行測試的字串。
+ `regex`：要比對的規則表達式模式。
+ `options`：（選用） 修改規則表達式行為的旗標，例如不區分大小寫的比對 (`i`) 或多行比對 ()`m`。

## 範例 (MongoDB Shell)
<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 Shell)
<a name="replaceAll-examples"></a>

下列範例示範如何在彙總管道中使用 `$replaceAll` 運算子，將字串 "Chocolatier" 的所有出現取代為 "Chocolate Co."。在「產品」集合的「brandName」欄位中。

**建立範例文件**

```
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`：用來取代 input(field) 中第一次出現的 find 的字串。

## 範例 (MongoDB Shell)
<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 Shell)
<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 版的新功能

Elastic 叢集不支援。

Amazon DocumentDB `$replaceWith` 中的彙總階段用於將輸入文件取代為新文件。輸入文件上的所有現有欄位，包括 \$1id 欄位，都會被新文件取代。 `$replaceWith` 通常用來扁平化文件，或將內嵌文件提升至頂層。

**參數**
+ `<replacement>` （必要）：將取代現有文件的新文件。

## 範例 (MongoDB Shell)
<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 Shell)
<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 版的新功能。

Elastic 叢集不支援。

Amazon DocumentDB 中的`$rtrim`運算子用於從字串中移除結尾字元。根據預設，它會移除結尾空白字元，但您也可以透過傳遞字元引數來指定要移除的一組字元。

**參數**
+ `input`：要從中移除結尾空格字元的輸入字串。
+ `chars`：（選用） 移除特定字元。

## 範例 (MongoDB Shell)
<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 Shell)
<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 份已隨機取樣。您現在可以使用這些文件來判斷平均值或執行最小/最大計算。

## 程式碼範例
<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 Shell)
<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 Shell)
<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 版的新功能

Elastic 叢集不支援。

Amazon DocumentDB `$set` 中的彙總階段可讓您在彙總管道期間新增欄位或更新文件中現有的欄位值。

**參數**
+ `expression`：要評估的表達式。這可以是任何有效的彙總表達式，包括欄位參考和算術操作。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<a name="slice-examples"></a>

下列範例示範如何使用 `$slice`傳回每個 Chef 的前兩個最愛甜食。

**建立範例文件**

```
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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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üsseldorf-BVV-021」字串的長度為 19 個位元組，不同於程式碼點 (18) 的數量，因為 Unicode 字元「Ü」佔用 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 Shell)
<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 }
```

請注意 "Düsseldorf-BVV-021" 字串的長度測量差異，其中包含 Unicode 字元 (Ü)。`$strLenCP` 運算子會正確計算 Unicode 字元的數量，而`$strLenBytes`運算子則會計算位元組的數量。

## 程式碼範例
<a name="strLenCP-code"></a>

若要檢視使用 `$strLenCP`命令的程式碼範例，請選擇您要使用的語言標籤：

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

以下是在 Node.js 應用程式中搭配 MongoDB 驅動程式使用 `$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 ]

以下是在 Python 應用程式中搭配 PyMongo 驅動程式使用 `$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 Shell)
<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 Shell)
<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`運算子用於根據指定的位元組範圍從字串中擷取子字串。當您需要從字串中擷取子字串，且代表字串中每個字元所需的位元組數很重要時，此運算子非常有用。

與在 Unicode 程式碼點數量上運作`$substrCP`的 不同， 以代表字串中字元所需的位元組數量`$substrBytes`運作。這在使用包含非 ASCII 字元的字串時特別有用，因為這些字元可能需要多個位元組才能表示。

\$1注意：\$1 自 3.4 版以來`$substr`已棄用。 現在`$substr`是 的別名。 `$substrBytes`

**參數**
+ `string`：將從中擷取子字串的輸入字串。
+ `startByte`：要擷取之子字串的以零為基礎的起始位元組位置。負值可用來從字串結尾指定位置。
+ `length`：子字串中要擷取的位元組數。

## 範例 (MongoDB Shell)
<a name="substrBytes-examples"></a>

在此範例中，我們將使用 從包含非 ASCII 字元的字串中`$substrBytes`擷取子字串。

**建立範例文件**

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

在此範例中，我們使用 從 `Desk` 欄位的第 12 個位元組開始`$substrBytes`擷取 3 個位元組的子字串。這可讓我們擷取 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 Shell)
<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 Shell 範例。

------

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

Amazon DocumentDB 中的`$subtract`運算子用於減去值。它可以用來減去日期、數字或兩者的組合。此運算子有助於計算兩個日期之間的差異，或從數字中減去值。

**參數**
+ `expression1`：要減去的第一個值。
+ `expression2`：要從 中減去的第二個值`<expression1>`。

## 範例 (MongoDB Shell)
<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 Shell)
<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 版的新功能。

Elastic 叢集不支援。

`$switch` 運算子是 Amazon DocumentDB 中的條件式表達式運算子，可讓您評估案例表達式清單，並傳回評估為 true 的第一個案例的值，如果沒有案例表達式為 true，則傳回預設值。

**參數**
+ `branches`：文件陣列，每個文件都有一個案例欄位，其中包含要評估的布林表達式，以及一個接著欄位，其中包含案例表達式為 true 時要傳回的值。
+ `default`：（選用） 如果沒有任何案例表達式為 true 時要傳回的值。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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`運算子用於將任何類型的值 ( null 除外） 轉換為字串表示法。當您需要對原本不是字串格式的值執行字串操作時，這會很有用。

**參數**
+ `expression`：要轉換為字串的表達式。

## 範例 (MongoDB Shell)
<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 Shell)
<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`運算子用於從字串中移除開頭和/或結尾空格字元。

**參數**
+ `input`：要修剪的字串表達式。
+ `chars`：（選用） 指定要從輸入開頭和結尾修剪的字元，預設值為空格。

## 範例 (MongoDB Shell)
<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 Shell)
<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 版的新功能

Elastic 叢集不支援。

Amazon DocumentDB 中的`$unset`彙總階段可讓您從文件中移除欄位。

**參數**
+ `expression`：欄位名稱或多個欄位名稱的清單。

## 範例 (MongoDB Shell)
<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`：（選用） 決定當陣列欄位為 null 或空白陣列時，操作會保留原始文件。

## 範例 (MongoDB Shell)
<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()
```

------

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

8.0 版的新功能

Elastic 叢集不支援。

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

------

# Geospatial (地理空間)
<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`，以對您的資料執行空間查詢。

在 Amazon DocumentDB 中，`$geometry`運算子支援下列 GeoJSON 幾何類型：
+ 點 (Point)
+ LineString
+ 多邊形
+ MultiPoint
+ MultiLineString
+ MultiPolygon
+ GeometryCollection

**參數**
+ `type`：GeoJSON 幾何物件的類型，例如 、 `Point``Polygon`等。
+ `coordinates`：代表幾何的座標陣列。座標陣列的結構取決於幾何類型。

## 範例 (MongoDB Shell)
<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`、`Polygon`、 `LineString`和 `MultiPolygon`。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Point 資料上的地理空間查詢需要。

## 範例 (MongoDB Shell)
<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 Point 查詢範例**

```
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 Shell)
<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 Shell)
<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`內使用](functional-differences.md#functional-differences.elemMatch) 如需在`$all`表達式中使用`$elemMatch`運算子的限制，請參閱 。

 

**欄位名稱中的美元 (\$1)**

[欄位名稱中的 Dollar(\$1) 和 dot(.)](functional-differences.md#functional-differences-dollardot) 如需在巢狀物件`$all`中查詢字`$`首欄位的限制，請參閱 。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<a name="bitsAllClear-examples"></a>

下列範例示範 Amazon DocumentDB 中`$bitsAllClear`運算子的使用情況。

**建立範例文件**

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

查詢會檢查位元遮罩指定的所有位元 `0b0011`（兩個最不重要的位元） 是否在 `bits` 欄位中清除。具有 `_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 Shell)
<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 Shell)
<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 Shell)
<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 }
```

查詢會傳回至少`0b1010`在 `flags` 欄位中設定一個位元遮罩中指定的位元的文件。

## 程式碼範例
<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 Shell)
<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`運算子用於查詢陣列欄位，並傳回陣列中至少有一個元素符合指定條件的文件。當您具有具有巢狀陣列或內嵌文件的複雜資料結構時，此運算子特別有用。

規劃器 2.0 版已新增 的索引支援。 `$elemMatch`

**參數**
+ `field`：要查詢的陣列欄位。
+ `query`：比對陣列元素的條件。

 

**在`$all`表達式`$elemMatch`內使用**

[在`$all`表達式`$elemMatch`內使用](functional-differences.md#functional-differences.elemMatch) 如需在`$all`表達式中使用`$elemMatch`運算子的限制，請參閱 。

## 範例 (MongoDB Shell)
<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 Shell)
<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` 運算子用於檢查某個欄位是否存在於文件中。在 Amazon DocumentDB 中使用稀疏索引時`$exists`特別有用，其中索引欄位可能不存在於所有文件中。

若要使用您在查詢中建立的稀疏索引，您必須在涵蓋索引的欄位上使用 `$exists` 子句。如果您省略 `$exists`，Amazon DocumentDB 將不會使用查詢的稀疏索引。

**參數**
+ `field`：要檢查是否存在的欄位名稱。
+ `value`：布林值 (`true` 或 `false`)，指定相符文件中的欄位是否應該存在 (`true`) 或不存在 (`false`)。

## 範例 (MongoDB Shell)
<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 版的新功能。

Elastic 叢集不支援。

Amazon DocumentDB 中的`$expr`運算子可讓您在查詢語言中使用彙總表達式。它可讓您對文件中的欄位執行複雜的比較和運算，類似於您使用彙總管道階段的方式。

**參數**
+ `expression`：傳回布林值的表達式，可讓您對文件欄位執行比較和運算。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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, ...]`：要比對指定欄位的值陣列。

 

**欄位名稱中的美元 (`$`)**

[欄位名稱中的 Dollar(\$1) 和 dot(.)](functional-differences.md#functional-differences-dollardot) 如需在巢狀物件`$in`中查詢字`$`首欄位的限制，請參閱 。

## 範例 (MongoDB Shell)
<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 版的新功能。

Elastic 叢集不支援。

Amazon DocumentDB 中的`$jsonSchema`運算子用於根據指定的 JSON 結構描述篩選文件。此運算子可讓您查詢符合特定 JSON 結構描述的文件，確保擷取的文件符合特定的結構和資料類型需求。

使用`$jsonSchema`評估查詢運算子作為集合建立的一部分，您可以驗證要插入集合的文件結構描述。如需其他資訊[使用 JSON 結構描述驗證](json-schema-validation.md)，請參閱 。

**參數**
+ `required` （陣列）：指定文件中的必要欄位。
+ `properties` （物件）：定義文件中每個欄位的資料類型和其他限制條件。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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` 運算子用於比對欄位值不等於指定值的文件。它是一種比較運算子，可用於查詢述詞來篩選文件。

規劃器 2.0 版已新增 的索引支援。 `$ne`

**參數**
+ `field`：要檢查的欄位。
+ `value`：要檢查的值。

## 範例 (MongoDB Shell)
<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`運算子的反向，其符合指定陣列中的值。

規劃器 2.0 版已新增 的索引支援。 `$nin`

**參數**
+ `field`：要檢查的欄位。
+ `array`：要檢查的值陣列。

 

**欄位名稱中的美元 (`$`)**

[欄位名稱中的 Dollar(\$1) 和 dot(.)](functional-differences.md#functional-differences-dollardot) 如需在巢狀物件`$nin`中查詢字`$`首欄位的限制，請參閱 。

## 範例 (MongoDB Shell)
<a name="nin-examples"></a>

下列範例示範如何使用 `$nin`運算子來尋找`category`欄位不等於 "Fiction" 或 "Mystery" 的文件。

**建立範例文件**

```
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` 運算子用於比對沒有任何指定查詢條件為 true 的文件。它類似於邏輯「NOR」操作，如果沒有任何運算元為 true，則結果為 true。

**參數**
+ `expression1`：要評估的第一個表達式。
+ `expression2`：要評估的第二個表達式。
+ `expressionN`：要評估的其他表達式。

## 範例 (MongoDB Shell)
<a name="nor-examples"></a>

下列範例會擷取`qty`欄位不小於 20 且`size`欄位不等於「XL」的文件，以示範`$nor`運算子的使用情況。

**建立範例文件**

```
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` 運算子用於否定指定表達式的結果。它可讓您選取指定條件不相符的文件。

規劃器 2.0 版新增了 `$not {eq}`和 的索引支援。 `$not {in}`

**參數**
+ `expression`：要否定的表達式。

## 範例 (MongoDB Shell)
<a name="not-examples"></a>

下列範例示範如何使用 `$not`運算子來尋找`status`欄位不等於「作用中」的文件。

**建立範例文件**

```
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 Shell)
<a name="or-examples"></a>

下列範例示範 `$or`運算子的用法，以尋找 `make`為 "TruckForYou" 且模型為 "Heavy H1" 或 "SportForYou" 且模型為 "Bolid 1" 的文件。

**建立範例文件**

```
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 Shell)
<a name="regex-examples"></a>

以下範例示範 `$regex`運算子的使用情況，以搜尋 "name" 欄位符合特定模式的文件。

**建立範例文件**

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

此查詢將傳回 "name" 欄位以字母 "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 Shell)
<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 Shell)
<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 Shell)
<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" }
```

上述命令會傳回具有文字索引欄位的文件，其中包含任何形式的「興趣」和等於 5 的「star\$1rating」。

## 程式碼範例
<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 類型。傳回的類型是字串，對應至欄位或表達式的類型。

規劃器 2.0 版已新增 的索引支援。 `$type`

**參數**
+ `expression` ：要評估的表達式。

## 範例 (MongoDB Shell)
<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` 欄位類型為 "number"、 `email` 欄位類型為 "string" 且 `name` 欄位類型為 "string" 的文件。

## 程式碼範例
<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>

本節提供有關 Amazon DocumentDB 支援的更新運算子的詳細資訊。

**Topics**
+ [\$1](dollar-update.md)
+ [\$1[]](dollarBrackets-update.md)
+ [\$1[<identifier>]](dollarIdentifier-update.md)
+ [\$1addToSet](addToSet.md)
+ [\$1bit](bit.md)
+ [\$1currentDate](currentDate.md)
+ [\$1each](each.md)
+ [\$1inc](inc.md)
+ [\$1max](max-update.md)
+ [\$1min](min-update.md)
+ [\$1mul](mul.md)
+ [\$1pop](pop.md)
+ [\$1position](position.md)
+ [\$1pull](pull.md)
+ [\$1pullAll](pullAll.md)
+ [\$1push](push.md)
+ [\$1rename](rename.md)
+ [\$1set](set-update.md)
+ [\$1setOnInsert](setOnInsert.md)
+ [\$1slice](slice-update.md)
+ [\$1sort](sort-update.md)
+ [\$1unset](unset-update.md)

# \$1
<a name="dollar-update"></a>

`$` 位置運算子會更新符合查詢條件的第一個陣列元素。它可做為相符陣列元素位置的預留位置。

**參數**
+ `field.$`：具有位置運算子的陣列欄位，用於更新第一個相符的元素。

## 範例 (MongoDB Shell)
<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>

`$[]` 所有位置運算子都會更新陣列中的所有元素。當您需要修改陣列欄位中的每個元素時，會使用它。

**參數**
+ `field.$[]`：具有所有位置運算子的陣列欄位，用於更新所有元素。

## 範例 (MongoDB Shell)
<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 Shell)
<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 Shell)
<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`運算子會將 "green" 標籤新增至文件的 "tags" 陣列，其中 "item" 欄位為 "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`：用於對 欄位執行位元 AND 操作的整數值。
+ `or`：整數值，用於對 欄位執行位元 OR 操作。
+ `xor`：整數值，用於對 欄位執行位元 XOR 操作。

## 範例 (MongoDB Shell)
<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`子用於對 文件的「數字」欄位執行位元 AND 操作，其中 `_id`為 1。結果是 "number" 欄位的值設定為 1，這是原始值 5 與值 3 之間的位元 AND 操作的結果。

## 程式碼範例
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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 Shell)
<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`：要從中移除值的陣列欄位名稱 (s)。
+ `value`：決定要從陣列中移除哪個元素的值或條件 (s)。

## 範例 (MongoDB Shell)
<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`欄位為「義大利文」的所有文件中移除「擷取」功能。

## 程式碼範例
<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 Shell)
<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 Shell)
<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
}
```

執行更新後，具有 的文件`_id: 1`會將`hobbies`陣列更新為 `[&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 Shell)
<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 驅動程式中的基本更新運算子，與 Amazon DocumentDB 相容。

**參數**
+ `field`：要更新的欄位。
+ `value`： 欄位的新值。

## 範例 (MongoDB Shell)
<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 Shell)
<a name="setOnInsert-examples"></a>

下列範例示範 Amazon DocumentDB 中`$setOnInsert`運算子的使用情況。如果文件尚未存在，它會建立新的文件，但如果文件正在更新，則不會有任何影響。

**建立範例文件**

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

`$slice` 更新運算子透過限制陣列的大小來修改陣列。與`$push`運算子搭配使用時，它會限制陣列中的元素數量，只保留指定數量的最新或最舊的元素。

**參數**
+ `field`：要修改的陣列欄位。
+ `count`：要保留的元素數目上限。正值保留前 N 個元素，負值保留最後 N 個元素。

## 範例 (MongoDB Shell)
<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>

與`$push`運算子搭配使用時，`$sort`更新修飾詞會訂購陣列元素。它會根據指定的欄位值或元素本身，以遞增或遞減順序排列陣列元素。

**參數**
+ `field`：要修改的陣列欄位。
+ `order`：`1`用於遞增順序或用於`-1`遞減順序。

## 範例 (MongoDB Shell)
<a name="sort-update-examples"></a>

下列範例示範搭配 `$sort` 使用修飾詞`$push`來新增新的測驗分數，並依遞減順序進行排序。

**建立範例文件**

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

------