

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon DocumentDB でサポートされている MongoDB API、オペレーション、およびデータ型
<a name="mongo-apis"></a>

Amazon DocumentDB (MongoDB 互換) は、MongoDB ワークロードをサポートする、高速、スケーラブル、高可用性、完全管理のドキュメントデータベース・サービスです。Amazon DocumentDB は、MongoDB 3.6、4.0、5.0、および 8.0 APIs。このセクションでは、サポートされている機能を一覧表示します。MongoDB API とドライバの使用のサポートについては、MongoDB コミュニティフォーラムを参照してください。Amazon DocumentDB サービスの使用に関するサポートについては、適切な AWS サポートチームにお問い合わせください。Amazon DocumentDB と MongoDB の機能的な違いについては、[機能の違い: Amazon DocumentDB と MongoDB](functional-differences.md) を参照してください。

内部専用であるか、フルマネージドサービスには適用されない、MongoDB コマンドと演算子は、サポートされておらず、サポートされている機能のリストにも含まれていません。

初めてのリリース以来 50 を超える新しい機能を追加しており、今後もお客様が必要とする機能を遡って提供していきます。最新のローンチに関する情報は、「[Amazon DocumentDB に関する発表](https://aws.amazon.com/documentdb/resources/)」を参照してください。

サポート対象外の機能をリクエストしたい場合は、アカウント ID、リクエストする機能、およびユースケースを記載した E メールを [Amazon DocumentDB サービスチーム](mailto:documentdb-feature-request@amazon.com) まで送信してお知らせください。
+ [データベースコマンド](#mongo-apis-database)
+ [クエリおよびプロジェクション演算子](#mongo-apis-query)
+ [更新演算子](#mongo-apis-update)
+ [地理空間](#mongo-apis-geospatial)
+ [カーソルメソッド](#mongo-apis-cursor)
+ [集約パイプライン演算子](#mongo-apis-aggregation-pipeline)
+ [データ型](#mongo-apis-data-types)
+ [インデックス](#mongo-apis-indexes)

## データベースコマンド
<a name="mongo-apis-database"></a>

**Topics**
+ [管理コマンド](#mongo-apis-dababase-administrative)
+ [集計](#mongo-apis-dababase-aggregation)
+ [認証](#mongo-apis-dababase-authentication)
+ [診断コマンド](#mongo-apis-dababase-diagnostics)
+ [クエリ操作と書き込み操作](#mongo-apis-dababase-query-write)
+ [ロール管理コマンド](#mongo-apis-database-role-management)
+ [セッションコマンド](#mongo-apis-dababase-sessions)
+ [ユーザー管理](#mongo-apis-dababase-user-management)
+ [シャーディングコマンド](#mongo-apis-dababase-sharding)

### 管理コマンド
<a name="mongo-apis-dababase-administrative"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  上限付きコレクション  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  aggregate  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  count  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  distinct  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  mapReduce  |  いいえ  |  なし  |  なし  |  あり  |  なし  | 

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


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  認証  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  ログアウト  |  はい   |  はい  |  はい  |  はい  |  はい  | 

### 診断コマンド
<a name="mongo-apis-dababase-diagnostics"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  buildInfo  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  collStats  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  connPoolStats  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  connectionStatus  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  dataSize  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  dbHash  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  dbStats  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  explain  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  説明: executionStats  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|    の機能  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  hostInfo  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  listCommands  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  プロファイラー  |  [あり](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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  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)  |  なし  | 
|  削除  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  find  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  findAndModify  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  getLastError  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  getMore  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  getPrevError  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  GridFS  |  はい   |  はい  |  はい  |  あり  |  なし  | 
|  insert  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  parallelCollectionScan  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  resetError  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  更新  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  ReplaceOne  |  はい   |  はい  |  はい  |  はい  |  はい  | 

### ロール管理コマンド
<a name="mongo-apis-database-role-management"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  createRole  |  はい   |  はい  |  はい  |  あり  |  なし  | 
|  dropAllRolesFromDatabase  |  はい   |  はい  |  はい  |  あり  |  なし  | 
|  dropRole  |  はい   |  はい  |  はい  |  あり  |  なし  | 
|  grantRolesToRole  |  はい   |  はい  |  はい  |  あり  |  なし  | 
|  revokeRolesFromRole  |  はい   |  はい  |  はい  |  あり  |  なし  | 
|  revokePrivilegesFromRole  |  はい   |  はい  |  はい  |  あり  |  なし  | 
|  rolesInfo  |  はい   |  はい  |  はい  |  あり  |  なし  | 
|  updateRole  |  はい   |  はい  |  はい  |  あり  |  なし  | 

### セッションコマンド
<a name="mongo-apis-dababase-sessions"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  abortTransaction  |  いいえ  |  はい  |  はい  |  あり  |  なし  | 
|  commitTransaction  |  いいえ  |  はい  |  はい  |  あり  |  なし  | 
|  endSessions  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|   killAllSessions  |  いいえ  |  はい  |  はい  |  あり  |  なし  | 
|  killAllSessionsByPattern  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  killSessions  |  いいえ  |  はい  |  はい  |  あり  |  なし  | 
|  refreshSessions  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  startSession  |  いいえ  |  はい  |  はい  |  あり  |  なし  | 

### ユーザー管理
<a name="mongo-apis-dababase-user-management"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  createUser  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  dropAllUsersFromDatabase  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  dropUser  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  grantRolesToUser  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  revokeRolesFromUser  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  updateUser  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  usersInfo  |  はい   |  はい  |  はい  |  はい  |  はい  | 

### シャーディングコマンド
<a name="mongo-apis-dababase-sharding"></a>


| コマンド | Elastic クラスター | 
| --- | --- | 
|  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  |  いいえ  | 
|  split  |  いいえ  | 
|  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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1comment](comment.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 

### 比較演算子
<a name="mongo-apis-query-comparison-operators"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1exists](exists.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  [\$1type](type.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 

### 評価クエリ演算子
<a name="mongo-apis-query-evaluation-operators"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1bit](bit.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 

### フィールド演算子
<a name="mongo-apis-update-field"></a>


| オペレーター | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1each](each.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  [\$1position](position.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  [\$1slice](slice-update.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 
|  [\$1sort](sort-update.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 

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

### ジオメトリ指定子
<a name="mongo-apis-geospatial-geometry-specifiers"></a>


| クエリセレクター | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  \$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  \$1accumulator  |  -  |  -  |  いいえ  |  なし  |  なし  | 
|  [\$1addToSet](addToSet-aggregation.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 
|  [\$1avg](avg.md)  |  はい  |  はい  |  はい  |  はい  |  あり  | 
|  [\$1count](count.md)  |  -  |  -  |  なし  |  なし  |  いいえ  | 
|  \$1covariancePop  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  \$1covarianceSamp  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  \$1denseRank  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  \$1derivative  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  \$1documentNumber  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  \$1expMovingAvg  |  いいえ  |  なし  |  なし  |  なし  |  なし  | 
|  [\$1first](first.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 
|  \$1integral  |  いいえ  |  なし  |  なし  |  なし  |  なし  | 
|  [\$1last](last.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 
|  [\$1max](max.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 
|  [\$1min](min.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 
|  [\$1push](push-aggregation.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 
|  \$1rank  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  \$1shift  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  \$1stdDevPop  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  \$1stdDevSamp  |  いいえ  |  なし  |  なし  |  なし  |  なし  | 
|  [\$1sum](sum.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 

### 算術演算子
<a name="mongo-apis-aggregation-pipeline-arithmetic"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1type](type-aggregation.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 

### データサイズ演算子
<a name="mongo-apis-aggregation-pipeline-data-size"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  \$1binarySize  |  -  |  -  |  いいえ  |  なし  |  いいえ  | 
|  \$1bsonSize  |  -  |  -  |  いいえ  |  なし  |  いいえ  | 

### 日付演算子
<a name="mongo-apis-aggregation-pipeline-date"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1literal](literal.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 

### マージ演算子
<a name="mongo-apis-aggregation-pipeline-merge"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1mergeObjects](mergeObjects.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 

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


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1natural](natural.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 

### セット演算子
<a name="mongo-apis-aggregation-pipeline-set"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  \$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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1meta](meta-aggregation.md)  |  いいえ  |  なし  |  はい  |  あり  |  なし  | 
|  [\$1search](search.md)  |  なし  |  なし  |  はい  |  あり  |  なし  | 

### 型変換演算子
<a name="mongo-apis-aggregation-pipeline-type"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1convert](convert.md)  |  いいえ  |  はい  |  はい  |  はい  |  はい  | 
|  \$1isNumber  |  -  |  -  |  いいえ  |  なし  |  なし  | 
|  [\$1toBool](toBool.md)  |  なし  |  はい  |  はい  |  はい  |  あり  | 
|  [\$1toDate](toDate.md)  |  なし  |  はい  |  はい  |  はい  |  あり  | 
|  [\$1toDecimal](toDecimal.md)  |  なし  |  はい  |  はい  |  はい  |  あり  | 
|  [\$1toDouble](toDouble.md)  |  なし  |  はい  |  はい  |  はい  |  あり  | 
|  [\$1toInt](toInt.md)  |  なし  |  はい  |  はい  |  はい  |  あり  | 
|  [\$1toLong](toLong.md)  |  なし  |  はい  |  はい  |  はい  |  あり  | 
|  [\$1toObjectId](toObjectId.md)  |  なし  |  はい  |  はい  |  はい  |  あり  | 
|  [\$1toString](toString.md)  |  なし  |  はい  |  はい  |  はい  |  はい  | 

### 変数演算子
<a name="mongo-apis-aggregation-pipeline-variable"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1let](let.md)  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  [\$1map](map.md)  |  はい  |  はい  |  はい  |  はい  |  はい  | 

### その他の演算子
<a name="mongo-apis-aggregation-pipeline-misc"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  \$1getField  |  -  |  -  |  いいえ  |  なし  |  なし  | 
|  [\$1rand](rand.md)  |  -  |  -  |  なし  |  あり  |  なし  | 
|  \$1sampleRate  |  -  |  -  |  いいえ  |  なし  |  いいえ  | 

## データ型
<a name="mongo-apis-data-types"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  32 ビット整数 (int)  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  64 ビット整数 (long)  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  配列  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  バイナリデータ  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  ブール値  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  日付  |  可能  |  はい  |  はい  |  はい  |  はい  | 
|  DBPointer  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  DBRefs  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  Decimal128  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  Double  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  JavaScript  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  JavaScript (スコープ付き)  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  MaxKey  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  MinKey  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  Null  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  オブジェクト  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  ObjectId  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  正規表現  |  はい   |  はい  |  はい  |  はい  |  可能  | 
|  String  |  可能  |  はい  |  はい  |  はい  |  はい  | 
|  記号  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  タイムスタンプ  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  未定義  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 

## インデックスとインデックスプロパティ
<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 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  2dsphere  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  2d インデックス  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  複合インデックス  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  ハッシュインデックス  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  マルチキーインデックス  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  単一フィールドインデックス  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  テキストインデックス  |  いいえ  |  なし  |  はい  |  あり  |  なし  | 
|  ワイルドカード  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 

### インデックスプロパティ
<a name="mongo-apis-index-properties"></a>


| コマンド | 3.6 | 4.0 | 5.0 | 8.0 | Elastic クラスター | 
| --- | --- | --- | --- | --- | --- | 
|  背景  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  大文字と小文字を区別しない  |  いいえ  |  なし  |  なし  |  あり  |  なし  | 
|  [非表示]  |  いいえ  |  なし  |  なし  |  なし  |  いいえ  | 
|  部分的  |  なし  |  なし  |  はい  |  あり  |  なし  | 
|  スパース  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  テキスト  |  いいえ  |  なし  |  はい  |  あり  |  なし  | 
|  TTL  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  Unique  |  はい   |  はい  |  はい  |  はい  |  はい  | 
|  Vector  |  いいえ  |  なし  |  はい  |  あり  |  なし  | 

特定の MongoDB 演算子の詳細については、以下のトピックを参照してください。
+ [集約パイプライン演算子](mongo-apis-aggregation-pipeline-operators.md)
+ [地理空間](mongo-apis-geospatial-operators.md)
+ [プロジェクション演算子](#mongo-apis-projection-operators)
+ [更新演算子](mongo-apis-update-operators.md)

# 集約パイプライン演算子
<a name="mongo-apis-aggregation-pipeline-operators"></a>

このセクションでは、Amazon DocumentDB でサポートされている集約パイプライン演算子に関する詳細情報を提供します。

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

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

Amazon DocumentDB の `$$DESCEND`演算子は、`$redact`パイプラインステージ内で使用される特殊な位置配列演算子です。集約パイプラインに、ネストレベルに関係なく、現在のドキュメントに降下し、すべてのフィールドを処理するように指示します。

`$redact` ステージが`$$DESCEND`オペレータに遭遇すると、現在のドキュメント内のすべてのフィールドが表示されたままになり、パイプラインのさらに下流で処理されます。これは、ドキュメントの構造を維持しながら、条件に基づいて特定のフィールドを選択的に編集またはプルーニングする場合に便利です。

**パラメータ**

なし。

## 例 (MongoDB シェル)
<a name="DESCEND-examples"></a>

この例では、 `$$DESCEND` 演算子で `$redact`ステージを使用して、 `code`フィールドが「Reg」と等しいドキュメントを選択的に表示します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="DESCEND-code"></a>

`$$DESCEND` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

redactPatients();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

redact_patients()
```

------

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

`$$KEEP` システム変数は、現在のドキュメントまたはフィールドを変更せずに出力に含めるために、集約パイプラインの `$redact`ステージで使用されます。

**パラメータ**

なし

## 例 (MongoDB シェル)
<a name="KEEP-examples"></a>

次の例は、Amazon DocumentDB 集約パイプライン`$$KEEP`での の使用を示しています。ドキュメントは、アクセスが「パブリック」と等しい場合にのみ保持され、そうでない場合は削除されます。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="KEEP-code"></a>

`$$KEEP` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

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

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

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

```
from pymongo import MongoClient

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

db = client.test
articles = db.articles

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

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

client.close()
```

------

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

`$$PRUNE` システム変数は、集計パイプラインの `$redact`ステージとともに使用され、結果からドキュメントまたは埋め込みドキュメントレベルを除外します。条件が に評価されると`$$PRUNE`、現在のドキュメントまたはサブドキュメントが出力から削除されます。通常、 `$$DESCEND` (ドキュメントを保持およびトラバースするため) または `$$KEEP` (ドキュメントをすべてのレベルで保持するため) で使用されます。

**パラメータ**

なし。`$$PRUNE` システム変数はパラメータなしで使用され、 で使用する必要があります`$redact`。

## 例 (MongoDB シェル)
<a name="PRUNE-examples"></a>

次の例は、 `$$PRUNE`で を使用して 30 年以上前のユーザー`$redact`を結果から除外する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="PRUNE-code"></a>

`$$PRUNE` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

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

main();
```

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

```
from pymongo import MongoClient

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

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

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

------

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

Amazon DocumentDB の `$ROOT`演算子は、集約パイプライン内の入力ドキュメント全体を参照するために使用されます。これにより、ネストされたすべてのフィールドと構造を含む完全なドキュメントにアクセスして操作できます。

**パラメータ**

なし

## 例 (MongoDB シェル)
<a name="ROOT-examples"></a>

この例では`$ROOT`、 を使用して、元のドキュメント全体を、いつ処理されたかについてのメタデータとともにキャプチャする監査ログを作成する方法を示します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="ROOT-code"></a>

`$ROOT` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

createAuditLog();
```

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

```
from pymongo import MongoClient
from datetime import datetime

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

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

    print(result)
    client.close()

create_audit_log()
```

------

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

Amazon DocumentDB の `$abs`演算子は、数値の絶対値を返します。集約パイプラインで使用して、数値フィールドで数学演算を実行できます。

**パラメータ**
+ `number`: 絶対値が返される数値式。

## 例 (MongoDB シェル)
<a name="abs-examples"></a>

この例では、演算子を使用して数値フィールドの絶対値`$abs`を見つける方法を示します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="abs-code"></a>

`$abs` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

main();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

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

------

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

Amazon DocumentDB の `$add`演算子は、数値または日付を一緒に追加するために使用されます。数値フィールドで算術演算を実行したり、日付フィールドに複数の時間単位を追加して日付算術を実行したりできます。

**パラメータ**
+ `expression1`: 追加する最初の数値または日付。
+ `expression2`: 追加する 2 番目の数値または日付。
+ `expression3`: (オプション) 追加する追加の数字または日付。

## 例 (MongoDB シェル)
<a name="add-examples"></a>

次の例は、 `$add`演算子を使用して 2 つの数値を一緒に追加する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

この例では、 `$add`演算子を使用して各ドキュメントの `a`フィールドと `b`フィールドの値を追加し、結果を `sum`フィールドに保存します。

## コードの例
<a name="add-code"></a>

`$add` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

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

------

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

`$addToSet` 集計演算子は、各グループの指定された式から一意の値の配列を返します。`$group` ステージ内で使用して個別の値を蓄積し、重複を自動的に排除します。

**パラメータ**
+ `expression`: グループ内の各ドキュメントについて評価する式。

## 例 (MongoDB シェル)
<a name="addToSet-aggregation-examples"></a>

次の例は、 `$addToSet`演算子を使用して、顧客ごとに注文が行われた一意の都市を収集する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="addToSet-aggregation-code"></a>

`$addToSet` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB 集約パイプラインの `$addFields`ステージでは、新しい計算フィールドをドキュメントに追加できます。これは、派生データまたは変換されたデータをドキュメントに追加するのに役立ちます。

**パラメータ**
+ `newField`: 追加する新しいフィールドの名前。
+ `expression`: 新しいフィールドの値に解決される式。

## 例 (MongoDB シェル)
<a name="addFields-examples"></a>

次の例は、 `$addFields`を使用して、 `Inventory.OnHand` および フィールドに基づいてインベントリの合計`TotalInventory`を計算する新しい`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 シェル)
<a name="allElementsTrue-examples"></a>

次の例は、配列内のすべての要素が true であるかどうかをチェック`$allElementsTrue`するための の使用を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

この例では、クエリは`scores`配列内のすべての要素が 0 より大きいかどうかを確認します。`scores` 配列に 0 が含まれているため、 を持つドキュメント`&quot;name&quot;: &quot;Jane&quot;`は除外されます。0 は不正な値です。

## コードの例
<a name="allElementsTrue-code"></a>

`$allElementsTrue` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

  console.log(result);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

example()
```

------

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

`$and` 集計演算子は複数の式を評価し、すべての式が と評価された`true`場合にのみ を返します`true`。いずれかの式が の場合`false`、 を返します`false`。

**パラメータ**
+ `expressions`: 評価する式の配列。

## 例 (MongoDB シェル)
<a name="and-aggregation-examples"></a>

次の例では、 `$and`演算子を使用して、製品が複数の基準を満たしているかどうかを確認します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="and-aggregation-code"></a>

`$and` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

バージョン 4.0 の新機能

`$anyElementTrue` 演算子は、配列内のいずれかの要素が true かどうかを判断するために使用されます。

**パラメータ**
+ `field`: 評価する配列フィールド。

## 例 (MongoDB シェル)
<a name="anyElementTrue-examples"></a>

次の例は、配列内の要素が true であるかどうかをチェック`$anyElementTrue`するための の使用を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="anyElementTrue-code"></a>

`$anyElementTrue` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

  console.log(result);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

example()
```

------

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

Amazon DocumentDB の `$arrayElemAt`演算子を使用すると、インデックス位置によって配列から要素を取得できます。これは、ドキュメントの配列フィールド内の特定の要素にアクセスする必要がある場合に特に便利です。

**パラメータ**
+ `array`: 要素を取得する入力配列。
+ `index`: 取得する要素のゼロベースのインデックス位置。この値は負以外の整数である必要があります。

## 例 (MongoDB シェル)
<a name="arrayElemAt-examples"></a>

この例では、 `$arrayElemAt`演算子を使用して`miles`コレクション内の`flight_miles`配列から特定の要素を取得する方法を示します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

この例では、 `$arrayElemAt`演算子を使用して、各ドキュメントの`flight_miles`配列の最初と最後の要素を取得します。

## コードの例
<a name="arrayElemAt-code"></a>

`$arrayElemAt` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の `$arrayToObject`演算子は、 `$objectToArray`演算子の逆です。キーと値のペアドキュメントの配列を取得し、1 つのドキュメントに変換します。これは、キーと値のペアの配列をオブジェクトまたはドキュメント構造に変換する必要がある場合に特に便利です。

**パラメータ**
+ `array expression`: 配列に解決される式。配列要素は、 ( キー) と `k` ( 値) の 2 `v` つのフィールドを持つドキュメントである必要があります。

## 例 (MongoDB シェル)
<a name="arrayToObject-examples"></a>

以下の例は、 `$arrayToObject`を使用してキーと値のペアの配列をドキュメントに変換する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

この例では、 `$objectToArray`演算子を使用して`inventory`オブジェクトをキーと値のペアの配列に変換します。次に、 `$arrayToObject`演算子を使用して配列をドキュメントに変換し、元のオブジェクト構造を復元します。

## コードの例
<a name="arrayToObject-code"></a>

`$arrayToObject` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の`$avg`集計演算子は、ステージに入力されるドキュメント全体で指定された式の平均値を計算します。この演算子は、一連のドキュメントにわたる数値フィールドまたは式の平均を計算するのに役立ちます。

**パラメータ**
+ `expression`: 平均の計算に使用する式。これは、フィールドパス (例: `"$field"`) または式 (例: `{ $multiply: ["$field1", "$field2"] }`) です。

## 例 (MongoDB シェル)
<a name="avg-examples"></a>

次の例は、 `$avg`演算子を使用して、一連の学生ドキュメントの平均スコアを計算する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="avg-code"></a>

`$avg` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

calculateAvgScore();
```

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

```
from pymongo import MongoClient

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

calculate_avg_score()
```

------

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

バージョン 8.0 の新機能

Elastic クラスターではサポートされていません。

Amazon DocumentDB の`$bucket`集約ステージでは、指定された式とバケットの境界に基づいて入力ドキュメントをバケットにグループ化できます。これは、特定の値の範囲またはカテゴリに含まれるデータの分析に役立ちます。

**パラメータ**
+ `groupBy` (必須): グループ化する値を指定する式。
+ `boundaries` (必須): バケットの境界を定義する二重値の配列。ドキュメントは、指定された境界内にある`groupBy`式の値に基づいてバケットに割り当てられます。
+ `default` (オプション): `groupBy`式値が指定された境界のいずれにも入らないドキュメントに対して出力されるリテラル値。
+ `output` (オプション): 各バケットに出力する情報を指定するオブジェクト。、`$sum`、`$avg`、 などのアキュムレータ演算子を使用して`$min`、各バケットの集計を`$max`計算できます。

## 例 (MongoDB シェル)
<a name="bucket-examples"></a>

次の例は、 `$bucket`ステージを使用して、価格範囲別に売上データをグループ化する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="bucket-code"></a>

`$bucket` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

バージョン 4.0 の新機能

Amazon DocumentDB の `$ceil`演算子は、MongoDB と同様に、数値を最も近い整数に切り上げます。これは、数値フィールドで数学演算を実行し、結果が整数であることを確認する必要がある場合に便利です。

**パラメータ**
+ `expression`: 切り上げる数値式。

## 例 (MongoDB シェル)
<a name="ceil-examples"></a>

この例では、 `$ceil`演算子を使用して数値フィールドを四捨五入する方法を示します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="ceil-code"></a>

`$ceil` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Elastic クラスターではサポートされていません。

`$changeStream` 集約ステージは変更ストリームカーソルを開き、コレクションへのリアルタイムの変更をモニタリングします。挿入、更新、置換、または削除オペレーションが発生すると、変更イベントドキュメントが返されます。

**パラメータ**
+ `fullDocument`: 更新オペレーションのために完全なドキュメントを返すかどうかを指定します。オプションは `default` または `updateLookup` です。
+ `resumeAfter`: オプション。トークンを再開して、変更ストリームの特定のポイントから続行します。
+ `startAtOperationTime`: オプション。変更ストリームを開始するタイムスタンプ。
+ `allChangesForCluster`: オプション。ブール値。の場合`true`、 はクラスター全体のすべての変更を監視します (管理者データベース用）。`false` (デフォルト) の場合、 は指定されたコレクションのみを監視します。

## 例 (MongoDB シェル)
<a name="changeStream-examples"></a>

次の例は、 `$changeStream`ステージを使用してコレクションの変更をモニタリングする方法を示しています。

**クエリの例**

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

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

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

**出力**

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

## コードの例
<a name="changeStream-code"></a>

`$changeStream` 集約ステージを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient
import threading
import time

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

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

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

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

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

    client.close()

example()
```

------

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

Amazon DocumentDB の `$cmp`演算子は、2 つの値を比較し、相対的な順序を示す整数値を返すために使用されます。これは、2 つの式を比較し、最初の値がそれぞれ 2 番目の値より小さい、等しい、または大きいかどうかに応じて、-1、0、または 1 の整数値を返す比較演算子です。

**パラメータ**
+ `expression1`: 比較する最初の式。
+ `expression2`: 比較する 2 番目の式。

## 例 (MongoDB シェル)
<a name="cmp-examples"></a>

次の例は、`$cmp`演算子を使用して 2 つの数値を比較する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

この例では、 `$cmp`演算子は各ドキュメントの フィールド`value1`と `value2`フィールドを比較します。結果は、次のとおりです。

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

## コードの例
<a name="cmp-code"></a>

`$cmp` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

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

`mongodb` ドライバーで Node.js アプリケーションで `$cmp`演算子を使用する例を次に示します。

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

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

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

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

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

  console.log(result);

  await client.close();
}

main();
```

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

`pymongo` ドライバーで Python アプリケーションで `$cmp`演算子を使用する例を次に示します。

```
from pymongo import MongoClient

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

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

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

print(result)

client.close()
```

Node.js と Python の両方の例の出力は、MongoDB シェルの例と同じになります。

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

------

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

バージョン 4.0 の新機能

Amazon DocumentDB の`$collStats`集約ステージは、MongoDB シェルの `db.collection.stats()` コマンドと同様に、指定されたコレクションに関する統計を提供します。このステージを使用して、ドキュメントの数、コレクションの合計サイズ、さまざまなパフォーマンスメトリクスなど、コレクションに関する情報を取得できます。

**パラメータ**
+ `latencyStats`: (オプション) レイテンシー統計を収集するためのオプションを指定するドキュメント。このパラメータは Amazon DocumentDB ではサポートされていません。
+ `recordStats`: (オプション) レコード統計を収集するためのオプションを指定するドキュメント。このパラメータは Amazon DocumentDB ではサポートされていません。
+ `queryExecStats`: (オプション) クエリ実行統計を収集するためのオプションを指定するドキュメント。このパラメータは Amazon DocumentDB ではサポートされていません。

## 例 (MongoDB シェル)
<a name="collStats-examples"></a>

次の例は、`$collStats`集約ステージを使用して、`db`データベース`test`内の という名前のコレクションに関する統計を取得する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="collStats-code"></a>

`$collStats` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

以下は、公式の MongoDB Node.js ドライバーを使用して Node.js アプリケーションで`$collStats`集約ステージを使用する方法の例です。

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

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

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

  console.log(result);

  await client.close();
}

runCollStatsExample();
```

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

PyMongo ドライバーを使用して Python アプリケーションで`$collStats`集約ステージを使用する方法の例を次に示します。

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

run_coll_stats_example()
```

------

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

Amazon DocumentDB の`$concat`集計演算子は、ドキュメント内の複数の文字列を連結 (または結合) して、アプリケーションに返すことができる単一の文字列を生成します。これにより、文字列操作がデータベースレベルで実行されるため、アプリケーションで実行される作業が減ります。

**パラメータ**
+ `expression1`: 連結する最初の文字列。
+ `expression2`: 連結する 2 番目の文字列。
+ `...`: 連結する追加の文字列 (オプション）。

## 例 (MongoDB シェル)
<a name="concat-examples"></a>

この例では、ユーザーの姓名を連結して、各ユーザーのフルネームを生成します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="concat-code"></a>

`$concat` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

  console.log(result);

  await client.close();
}

concatenateNames();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

concatenate_names()
```

------

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

Amazon DocumentDB の`$concatArrays`集計演算子は、2 つ以上の配列を 1 つの配列に連結するために使用されます。これは、データの複数の配列を 1 つの配列に結合して、さらに処理または分析する必要がある場合に便利です。

**パラメータ**
+ `array1`: 連結する最初の配列。
+ `array2`: 連結する 2 番目の配列。
+ `[array3, ...]`: (オプション) 連結する追加の配列。

## 例 (MongoDB シェル)
<a name="concatArrays-examples"></a>

次の例は、 `$concatArrays`演算子を使用して 2 つの配列を 1 つの配列に結合する方法を示しています。

**サンプルドキュメントを作成する**

```
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`演算子は、条件式を評価し、2 つの可能な結果式のいずれかを返すために使用されます。

**パラメータ**
+ `if`: 評価するブール式。
+ `then`: 式が true の場合に返される`if`式。
+ `else`: 式が false の場合に返される`if`式。

## 例 (MongoDB シェル)
<a name="cond-examples"></a>

次の例は、 `$cond`演算子を使用して、人の年齢に基づいて値を返す方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="cond-code"></a>

`$cond` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient


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

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

    print(result)
    client.close()

example()
```

------

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

バージョン 4.0 の新機能

Amazon DocumentDB の `$convert`演算子は、あるデータ型から別のデータ型に値を変換するために使用されます。この演算子は、文字列を数値に変換したり、日付をタイムスタンプに変換したりするなど、さまざまなタイプのデータに対してオペレーションを実行する必要がある場合に便利です。

**パラメータ**
+ `to`: 値を変換するターゲットデータ型。サポートされている値は `"string"`、`"double"`、`"long"`、`"int"`、`"date"`、`"boolean"` です。
+ `from`: 値の現在のデータ型。指定しない場合、Amazon DocumentDB はデータ型を自動的に検出しようとします。
+ `onError`: (オプション) 変換が失敗した場合に返される値。特定の値、または次の特殊な値のいずれかを指定できます: `"null"`、`"zerofill"`、または `"error"`。
+ `onNull`: (オプション) 入力値が の場合に返される値`null`。特定の値、または次の特殊な値のいずれかを指定できます: `"null"`、`"zerofill"`、または `"error"`。

## 例 (MongoDB シェル)
<a name="convert-examples"></a>

次の例は、 `$convert`演算子を使用して文字列値を日付に変換する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="convert-code"></a>

`$convert` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(results)
    client.close()

example()
```

------

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

Amazon DocumentDB の`$count`集約ステージは、ステージに渡すドキュメントの数をカウントするために使用されます。多くの場合、前のステージに一致するドキュメントの合計数を返すために、集約パイプラインの最終ステージとして使用されます。

**パラメータ**
+ `field`: カウントするフィールド。このパラメータはオプションであり、指定しない場合、ステージは入力ドキュメントの総数をカウントします。

## 例 (MongoDB シェル)
<a name="count-examples"></a>

次の例は、 `$count`ステージを使用してコレクション内のドキュメントの総数を取得する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

この例では、`users`コレクションを集約し、 `$count`ステージを使用してドキュメントの総数をカウントします。

## コードの例
<a name="count-code"></a>

`$count` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

  await client.close();
}

countDocuments();
```

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

```
from pymongo import MongoClient

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

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

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

    client.close()

count_documents()
```

------

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

`$currentOp` 集約ステージは、データベースで現在実行中のオペレーションに関する情報を返します。このステージは、集約パイプラインでアクティブなクエリとオペレーションをモニタリングするのに役立ちます。

**パラメータ**
+ `allUsers` (オプション): に設定すると`true`、 はすべてのユーザーのオペレーションを返します。デフォルトは `false` です。
+ `idleConnections` (オプション): に設定すると`true`、 にはアイドル接続が含まれます。デフォルトは `false` です。
+ `idleCursors` (オプション): に設定すると`true`、 にはアイドルカーソルに関する情報が含まれます。デフォルトは `false` です。
+ `idleSessions` (オプション): に設定すると`true`、 にはアイドルセッションに関する情報が含まれます。デフォルトは `true` です。
+ `localOps` (オプション): に設定すると`true`、 にはローカルオペレーションが含まれます。デフォルトは `false` です。

## 例 (MongoDB シェル)
<a name="currentOp-examples"></a>

次の例は、`$currentOp`集約ステージを使用してアクティブな読み取りオペレーションに関する情報を取得する方法を示しています。

**クエリの例**

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

**出力**

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

## コードの例
<a name="currentOp-code"></a>

`$currentOp` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

バージョン 5.0 の新機能

Amazon DocumentDB の`$dateAdd`集計演算子を使用すると、日付と時刻の値に期間を追加できます。

**パラメータ**
+ `date`: 期間を追加する日付と時刻の値。
+ `duration`: `date`値に追加する期間。これは、、`years`、、`months`、`weeks`、、`days``hours``minutes`および のキーを持つオブジェクトとして指定できます`seconds`。
+ `timezone`: (オプション) 日付の追加を実行するときに使用するタイムゾーン。指定しない場合、Amazon DocumentDB クラスターのデフォルトのタイムゾーンが使用されます。

## 例 (MongoDB シェル)
<a name="dateAdd-examples"></a>

次の例は、 `$dateAdd`演算子を使用して日付に 2 日と 12 時間を追加する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="dateAdd-code"></a>

`$dateAdd` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

  console.log(result);

  await client.close();
}

example();
```

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

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

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

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

    print(result)

    client.close()

example()
```

------

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

バージョン 5.0 の新機能

Elastic クラスターではサポートされていません。

`$dateDiff` 集計演算子は、指定された単位で 2 つの日付の差を計算します。開始日と終了日の間の単位境界の数を返します。

**パラメータ**
+ `startDate`: 開始日の式。
+ `endDate`: 終了日式。
+ `unit`: 差の時間単位。サポートされている単位は、`year`、、`quarter`、`month`、`week`、`day`、`hour``minute``second`、、および です`millisecond`。

## 例 (MongoDB シェル)
<a name="dateDiff-examples"></a>

次の例は、 `$dateDiff`演算子を使用して、注文から配送までの日数を計算する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="dateDiff-code"></a>

`$dateDiff` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

example()
```

------

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

Amazon DocumentDB の`$dateFromString`集計演算子を使用すると、日時文字列を日付オブジェクトに変換できます。これは、データが文字列として保存されているが、データに対して日付ベースのオペレーションを実行する必要がある場合に便利です。

**パラメータ**
+ `dateString`: 日付と時刻を表す文字列。
+ `format`: (オプション) の形式を指定する文字列`dateString`。指定しない場合、Amazon DocumentDB は ISO-8601 形式で文字列の解析を試みます。
+ `timezone`: (オプション) タイムゾーンを指定する文字列。指定しない場合、Amazon DocumentDB はサーバーのタイムゾーンを使用します。
+ `onError`: (オプション) 変換が失敗した場合に実行するアクションを指定します。指定できる値は、 `'error'` (エラーをスローするデフォルト）、 `'null'` ( を返す`null`)、または `'replace'` ( 値を `onErrorMessage`オプションで指定された置換文字列に置き換えます) です。
+ `onErrorMessage`: (オプション) `onError`が に設定されている場合`'replace'`、このオプションは置き換え文字列を指定します。

## 例 (MongoDB シェル)
<a name="dateFromString-examples"></a>

次の例は、 `$dateFromString`を使用して Amazon DocumentDB の日付文字列を日付オブジェクトに変換する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="dateFromString-code"></a>

`$dateFromString` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

バージョン 5.0 の新機能

Amazon DocumentDB の`$dateSubtract`集計演算子を使用すると、指定された期間を日付値から減算できます。

**パラメータ**
+ `date`: 日付またはタイムスタンプに解決される日付式。
+ `subtrahend`: 式から減算する時間を指定する期間`date`式。
+ `unit`: `subtrahend`式の時間単位を指定する文字列。サポートされている単位は、「年」、「四半期」、「月」、「週」、「日」、「時間」、「分」、「秒」、「ミリ秒」です。

## 例 (MongoDB シェル)
<a name="dateSubtract-examples"></a>

次の例は、 `$dateSubtract`演算子を使用して、現在の日付から 1 年前の日付を計算する方法を示しています。

**サンプルドキュメントを作成する**

```
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`: 日付を表す形式を指定する文字列。形式文字列には、4 桁の年`%Y`、`%m`2 桁の月、2 `%d`桁の日など、さまざまな形式指定子を含めることができます。
+ `timezone`: (オプション) 変換に使用するタイムゾーン。指定しない場合、Amazon DocumentDB クラスターをホストするサーバーのタイムゾーンが使用されます。
+ `onNull`: (オプション) `date`パラメータが の場合に返される値`null`。

## 例 (MongoDB シェル)
<a name="dateToString-examples"></a>

次の例は、 `$dateToString`演算子を使用して`missionLog`コレクションの `logDate`フィールドをフォーマットする方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="dateToString-code"></a>

`$dateToString` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

Node.js アプリケーションで `$dateToString`演算子を使用する例を次に示します。

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

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

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

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

example();
```

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

Python アプリケーションで `$dateToString`演算子を使用する例を次に示します。

```
from pymongo import MongoClient

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

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

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

example()
```

------

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

バージョン 8.0 の新機能

Elastic クラスターではサポートされていません。

Amazon DocumentDB の`$dateTrunc`集計演算子は、指定された単位に日付を切り捨てます。

**パラメータ**
+ `date`: 日付またはタイムスタンプに解決される日付式。
+ `unit`: サブtrahend 式の時間単位を指定する文字列。サポートされている単位は、`year`、、`quarter`、`month`、`week`、`day`、`hour``minute``second`、、および です`millisecond`。

## 例 (MongoDB シェル)
<a name="dateTrunc-examples"></a>

次の例は、 `$dateTrunc`演算子を使用して日付を に切り捨てて 1 時間にする方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="dateTrunc-code"></a>

`$dateTrunc` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

example()
```

------

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

Amazon DocumentDB の`$dayOfMonth`集計演算子は、特定の日付の日 (1～31) を取得します。この演算子は、ドキュメントの日付フィールドから日付をグループ化、フィルタリング、または抽出するのに役立ちます。

**パラメータ**
+ `date expression`: 日付式は、ドキュメントの日付フィールド、日付オブジェクト、または日付文字列です。

## 例 (MongoDB シェル)
<a name="dayOfMonth-examples"></a>

この例では、 `$dayOfMonth`演算子を使用してドキュメントの日付フィールドから日付を抽出する方法を示します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="dayOfMonth-code"></a>

`$dayOfMonth` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の `$dayOfWeek`演算子は、特定の日付フィールドから曜日を抽出します。曜日を 1 (日曜日) から 7 (土曜日) までの数値として返します。これは MongoDB と同じ動作です。

**パラメータ**
+ `date field`: 曜日を抽出する日付フィールド。

## 例 (MongoDB シェル)
<a name="dayOfWeek-examples"></a>

この例では、 `$dayOfWeek`演算子を使用して、`weather`コレクションの `date`フィールドから曜日を抽出する方法を示します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="dayOfWeek-code"></a>

`$dayOfWeek` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

  console.log(result);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

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

------

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

Amazon DocumentDB の`$dayOfYear`演算子は、日付の日を 1～366 (うるう年以外の場合は 365) の数値として返します。

**パラメータ**
+ `expression`: 日を抽出する日付フィールドまたは式。

## 例 (MongoDB シェル)
<a name="dayOfYear-examples"></a>

この例では、 `$dayOfYear`演算子を使用して Amazon DocumentDB コレクションの日付フィールドから日付を抽出する方法を示します。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="dayOfYear-code"></a>

`$dayOfYear` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

  console.log(result);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

example()
```

------

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

Amazon DocumentDB 集約パイプラインの `$divide`演算子は、ある数値を別の数値で割るために使用されます。これは、ドキュメント内の数値フィールドに対して数学演算を実行するのに便利な演算子です。

**パラメータ**
+ `numerator`: 分割する分配または数値。
+ `denominator`: 除算器または除算する数値。

## 例 (MongoDB シェル)
<a name="divide-examples"></a>

この例では、 `$divide`演算子を使用して、年間給与と 1 年あたりの勤務時間数に基づいて従業員の時間単価を計算する方法を示します。

**サンプルドキュメントを作成する**

```
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` 集計演算子は 2 つの値を比較し、等しい`true`場合は を返し、そうでない場合は を返します`false`。

**パラメータ**
+ `expression1`: 比較する最初の値。
+ `expression2`: 比較する 2 番目の値。

## 例 (MongoDB シェル)
<a name="eq-aggregation-examples"></a>

次の例は、 `$eq`演算子を使用して、製品数量がターゲット値と一致するかどうかを確認する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="eq-aggregation-code"></a>

`$eq` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

バージョン 4.0 の新機能

Amazon DocumentDB の `$exp`演算子を使用すると、定数 e を特定の数値に上げることができます。

**パラメータ**
+ `expression`: 評価する式。これは、フィールド参照、算術演算、その他の集計ステージなど、任意の有効な集計式にすることができます。

## 例 (MongoDB シェル)
<a name="exp-examples"></a>

次の例は、 `$exp`演算子を使用して、 `quantity`フィールドが `price`フィールドより大きいすべてのドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="exp-code"></a>

`$exp` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

aggregateExp();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

aggregate_exp()
```

------

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

Amazon DocumentDB の `$filter`演算子は、配列の各要素にフィルター式を適用し、指定された条件に一致する要素のみを含む配列を返すために使用されます。この演算子は、ドキュメント内の配列フィールドに対して複雑なフィルタリングオペレーションを実行する必要がある場合に便利です。

**パラメータ**
+ `input`: フィルタリングする配列フィールド。
+ `as`: `cond`式内の`input`配列の各要素に使用する変数名。
+ `cond`: 特定の要素を出力配列に含めるかどうかを決定するブール式。

## 例 (MongoDB シェル)
<a name="filter-examples"></a>

次の例は、 `$filter`演算子を使用して各注文の顧客を射影し、価格が 15 より大きい商品配列の商品のみを含む新しい配列フィールド paidItems を作成する方法を示しています。基本的に、各注文の項目をフィルタリングして、コストが 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 シェル)
<a name="first-examples"></a>

次の例は、 `$first`演算子を使用して、集計中に各カテゴリで発生した最初の項目値を取得する方法を示しています。

注: は、パイプライン内のドキュメントの現在の順序に基づいて最初のドキュメント`$first`を返します。特定の順序 (日付、料金など) を確保するには、`$sort`ステージの前に`$group`ステージを使用する必要があります。

**サンプルドキュメントを作成する**

```
db.products.insertMany([
  { _id: 1, item: "abc", price: 10, category: "food" },
  { _id: 2, item: "jkl", price: 20, category: "food" },
  { _id: 3, item: "xyz", price: 5, category: "toy" },
  { _id: 4, item: "abc", price: 5, category: "toy" }
]);
```

**クエリの例**

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

**出力**

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

## コードの例
<a name="first-code"></a>

`$first` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('products');

    const result = await collection.aggregate([
      { $group: { _id: "$category", firstItem: { $first: "$item" } } }
    ]).toArray();

    console.log(result);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

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

```
from pymongo import MongoClient
from pprint import pprint

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

        db = client['test']
        collection = db['products']

        result = list(collection.aggregate([
            { '$group': { '_id': '$category', 'firstItem': { '$first': '$item' } } }
        ]))

        pprint(result)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        if client:
            client.close()

example()
```

------

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

バージョン 4.0 の新機能。

Amazon DocumentDB の `$floor`演算子は、指定された数以下の最大の整数を返します。この演算子は、数値を四捨五入するのに役立ちます。

**パラメータ**
+ `expression`: 切り捨てる数値式。

## 例 (MongoDB シェル)
<a name="floor-examples"></a>

次の例は、 `$floor`演算子を使用して 10 進値を最も近い整数に四捨五入する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="floor-code"></a>

`$floor` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('numbers');

    const result = await collection.aggregate([
      { $project: { _id: 0, floored: { $floor: "$value" } } }
    ]).toArray();

    console.log(result);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

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

```
from pymongo import MongoClient
from pprint import pprint

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

        db = client.test
        collection = db.numbers

        result = list(collection.aggregate([
            { '$project': { '_id': 0, 'floored': { '$floor': '$value' }}}
        ]))

        pprint(result)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        if client:
            client.close()

example()
```

------

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

`$geoNear` 集約ステージは、指定されたポイントに近接した順序でドキュメントを返します。ポイントからの距離を計算し、出力ドキュメントに距離を含めます。

**パラメータ**
+ `near`: GeoJSON またはレガシー座標として指定された距離を計算するポイント。
+ `distanceField`: 計算された距離を保存するフィールド名。
+ `spherical`: 球形ジオメトリを使用するかどうかを示すブール値 (GeoJSON ポイントに必要）。
+ `maxDistance`: オプション。中心点からの最大距離。
+ `minDistance`: オプション。中心点からの最小距離。
+ `query`: オプション。適用する追加のフィルター条件。
+ `limit`: オプション。返されるドキュメントの最大数。
+ `key`: オプション。複数の地理空間インデックスが存在する場合に地理空間クエリに使用するフィールド。

## 例 (MongoDB シェル)
<a name="geoNear-examples"></a>

次の例は、 `$geoNear`ステージを使用して、特定の場所に最も近いストアを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.stores.createIndex({ location: "2dsphere" });

db.stores.insertMany([
  { _id: 1, name: "Store A", location: { type: "Point", coordinates: [-122.4, 37.8] } },
  { _id: 2, name: "Store B", location: { type: "Point", coordinates: [-122.5, 37.7] } },
  { _id: 3, name: "Store C", location: { type: "Point", coordinates: [-122.3, 37.9] } }
]);
```

**クエリの例**

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

**出力**

```
[
  { _id: 1, name: 'Store A', location: { type: 'Point', coordinates: [ -122.4, 37.8 ] }, distance: 0 },
  { _id: 3, name: 'Store C', location: { type: 'Point', coordinates: [ -122.3, 37.9 ] }, distance: 13877.82 },
  { _id: 2, name: 'Store B', location: { type: 'Point', coordinates: [ -122.5, 37.7 ] }, distance: 15557.89 }
]
```

## コードの例
<a name="geoNear-code"></a>

`$geoNear` 集約ステージを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $geoNear: {
        near: { type: "Point", coordinates: [-122.4, 37.8] },
        distanceField: "distance",
        spherical: true
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$geoNear': {
                'near': { 'type': 'Point', 'coordinates': [-122.4, 37.8] },
                'distanceField': 'distance',
                'spherical': True
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の`$group`集約ステージでは、指定された式でドキュメントをグループ化し、グループ化されたデータに対してさまざまな累積オペレーションを実行できます。これは、グループ化されたデータに基づいて合計、平均、またはその他の統計を計算するなどのタスクに役立ちます。

**パラメータ**
+ `_id`: 入力ドキュメントをグループ化する式を指定します。これは、フィールド名、計算式、またはその両方の組み合わせです。
+ `accumulator expressions`: (オプション) グループ化されたデータに適用する必要がある 1 つ以上のアキュムレータ式。これらの式は、上記のアキュムレータ演算子を使用します。

## 例 (MongoDB シェル)
<a name="group-examples"></a>

次の例では、顧客を都市別にグループ化し、各都市の合計注文額を計算します。

**サンプルドキュメントを作成する**

```
db.customers.insertMany([
  { name: "John Doe", city: "New York", orders: [{ amount: 100 }, { amount: 200 }] },
  { name: "Jane Smith", city: "Los Angeles", orders: [{ amount: 150 }, { amount: 300 }] },
  { name: "Bob Johnson", city: "New York", orders: [{ amount: 75 }, { amount: 125 }] },
  { name: "Samantha Lee", city: "Chicago", orders: [{ amount: 50 }, { amount: 100 }] }
]);
```

**クエリの例**

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

**出力**

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

## コードの例
<a name="group-code"></a>

`$group` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  try {
    await client.connect();
    const db = client.db('test');
    const result = await db.collection('customers').aggregate([
      { $unwind: '$orders' },
      {
        $group: {
          _id: '$city',
          totalOrders: { $sum: '$orders.amount' }
        }
      }
    ]).toArray();

    console.log(result);
  } catch (err) {
    console.error('Error during aggregation:', err);
  } finally {
    await client.close();
  }
}

groupByCity();
```

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

```
from pymongo import MongoClient

def group_by_city():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    
    try:
        db = client.test
        result = list(db.customers.aggregate([
            {'$unwind': '$orders'},
            {
                '$group': {
                    '_id': '$city',
                    'totalOrders': {'$sum': '$orders.amount'}
                }
            }
        ]))
        print(result)
    except Exception as e:
        print(f"Error during aggregation: {e}")
    finally:
        client.close()

group_by_city()
```

------

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

`$gt` 集計演算子は 2 つの値を比較し、最初の値が 2 番目より大きい`true`場合は を返し、それ以外の場合は を返します`false`。

**パラメータ**
+ `expression1`: 比較する最初の値。
+ `expression2`: 比較する 2 番目の値。

## 例 (MongoDB シェル)
<a name="gt-aggregation-examples"></a>

次の例は、 `$gt`演算子を使用して、価格しきい値を超える製品を識別する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="gt-aggregation-code"></a>

`$gt` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        price: 1,
        expensive: { $gt: ["$price", 100] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'price': 1,
                'expensive': { '$gt': ['$price', 100] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$gte` 集計演算子は 2 つの値を比較し、最初の値が 2 番目以上の`true`場合は を返し、それ以外の場合は を返します`false`。

**パラメータ**
+ `expression1`: 比較する最初の値。
+ `expression2`: 比較する 2 番目の値。

## 例 (MongoDB シェル)
<a name="gte-aggregation-examples"></a>

次の例は、 `$gte`演算子を使用して、学生が試験に合格したかどうかを確認する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="gte-aggregation-code"></a>

`$gte` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        score: 1,
        passed: { $gte: ["$score", 70] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'score': 1,
                'passed': { '$gte': ['$score', 70] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$hour` 演算子は、日付またはタイムスタンプフィールドから時間コンポーネントを抽出します。

**パラメータ**
+ `dateExpression`: 演算子が適用される日付。これは有効な BSON 日付 (例: \$1createdAt のようなフィールドや日付リテラル) に解決する必要があります。

パラメータは、次の形式でドキュメントとして指定することもできます。

\$1 日付: `&lt;dateExpression&gt;`、タイムゾーン: `&lt;timezoneExpression&gt;` \$1

これにより、 はタイムゾーン対応の日付オペレーションを適用できます。

```
- `<tzExpression>`: (optional) The timezone of the operation result. It must be a valid expression that resolves to a string formatted as either an Olson Timezone Identifier or a UTC Offset. If no timezone is provided, the result is in UTC.
```

## 例 (MongoDB シェル)
<a name="hour-examples"></a>

次の例は、 `$hour`演算子を使用して日付フィールドから時間コンポーネントを抽出し、それに応じてデータをグループ化する方法を示しています。

**サンプルドキュメントを作成する**

```
db.events.insertMany([
  { timestamp: new Date("2023-04-01T10:30:00Z") },
  { timestamp: new Date("2023-04-01T12:45:00Z") },
  { timestamp: new Date("2023-04-02T08:15:00Z") },
  { timestamp: new Date("2023-04-02T16:20:00Z") },
  { timestamp: new Date("2023-04-03T23:59:00Z") }
]);
```

**クエリの例**

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

**出力**

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

このクエリは、 `timestamp`フィールドの時間コンポーネントでイベントをグループ化し、1 時間あたりのイベント数をカウントします。

## コードの例
<a name="hour-code"></a>

`$hour` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

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

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

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

    const result = await collection.aggregate([
      {
        $project: {
          hour: { $hour: "$timestamp" }
        }
      },
      {
        $group: {
          _id: "$hour",
          count: { $sum: 1 }
        }
      },
      {
        $sort: { _id: 1 }
      }
    ]).toArray();

    console.log(result);
  } catch (error) {
    console.error('Error occurred:', error);
  } finally {
    await client.close();
  }
}

example();
```

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

```
from pymongo import MongoClient
from datetime import datetime

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

        result = list(collection.aggregate([
            {
                "$project": {
                    "hour": {"$hour": "$timestamp"}
                }
            },
            {
                "$group": {
                    "_id": "$hour",
                    "count": {"$sum": 1}
                }
            },
            {
                "$sort": {"_id": 1}
            }
        ]))

        print(result)

    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        client.close()

example()
```

------

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

`$ifNull` 演算子は、入力式が null または未定義と評価された場合に、指定された値を返すために使用されます。この演算子は、デフォルト値を指定したり、null/undefined ケースを処理したりする場合に役立ちます。

**パラメータ**
+ `expression`: 評価する式。
+ `replacement`: が null または未定義と`<expression>`評価された場合に返される値。

## 例 (MongoDB シェル)
<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 シェル)
<a name="in-aggregation-examples"></a>

次の例では、 `$in`演算子を使用して、各従業員のスキルセットに特定のスキルが存在するかどうかを確認します。

**サンプルドキュメントを作成する**

```
db.employees.insertMany([
  { _id: 1, name: "Sarah", skills: ["Python", "JavaScript", "SQL"] },
  { _id: 2, name: "Mike", skills: ["Java", "C++", "Go"] },
  { _id: 3, name: "Emma", skills: ["Python", "Ruby", "Rust"] }
]);
```

**クエリの例**

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

**出力**

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

## コードの例
<a name="in-aggregation-code"></a>

`$in` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        hasPython: { $in: ["Python", "$skills"] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'hasPython': { '$in': ['Python', '$skills'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の `$indexOfArray`演算子は、配列内の指定された要素の最初の出現のインデックスを見つけるために使用されます。この演算子は、指定された値に一致する配列の最初の要素のゼロベースのインデックス位置を返します。値が見つからない場合は、-1 を返します。

**パラメータ**
+ `array`: 検索する配列。
+ `value`: 配列内で検索する値。
+ `start`: (オプション) 検索を開始する配列内の位置。デフォルト値は 0 です。

## 例 (MongoDB シェル)
<a name="indexOfArray-examples"></a>

次の例は、\$1indexOfArray 演算子を使用して、各ドキュメントの「fruits」配列で要素「mango」の最初の出現のインデックスを検索する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="indexOfArray-code"></a>

`$indexOfArray` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        fruitIndex: { $indexOfArray: ["$fruits", "mango"] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'fruitIndex': { '$indexOfArray': ["$fruits", "mango"] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の \$1indexOfBytes 演算子は、文字列内の部分文字列の開始インデックスを、文字のバイト位置に基づいて検索するために使用されます。これは、Latin 以外のスクリプトなど、複数バイトの文字を含むテキストデータを使用する場合に便利です。

**パラメータ**
+ `string`: 検索する入力文字列。
+ `substring`: 入力文字列内で検索する部分文字列。
+ `[<start>]`: (オプション) 検索の開始位置 (ゼロベース）。指定しない場合、検索は文字列の先頭から始まります。

## 例 (MongoDB シェル)
<a name="indexOfBytes-examples"></a>

次の例は、 を使用して、デスクの場所を表す文字列のセット内の最初のハイフン文字のインデックス`$indexOfBytes`を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
```

**クエリの例**

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

**出力**

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

## コードの例
<a name="indexOfBytes-code"></a>

`$indexOfBytes` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await db.collection('people').aggregate([
    { $project: { stateLocation: { $indexOfBytes: ["$Desk", "-"] } } }
  ]).toArray();
  console.log(result);
  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']
    
    result = list(db.people.aggregate([
        { '$project': { 'stateLocation': { '$indexOfBytes': ['$Desk', '-'] } } }
    ]))
    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の `$indexOfCP`演算子は、文字列式内で指定された部分文字列が最初に出現したときのインデックスをコードポイント (CP) で検索するために使用されます。これは、文字列フィールドからコンテンツを解析および抽出する場合に便利です。

**パラメータ**
+ `string expression`: 検索する文字列。
+ `substring`: 検索する部分文字列。
+ `[<start>]`: (オプション) 検索を開始する位置 (ゼロベースのインデックス）。デフォルトは 0 です。

## 例 (MongoDB シェル)
<a name="indexOfCP-examples"></a>

この例では、 `$indexOfCP`演算子を使用して、各ドキュメントの Desk フィールドでハイフン文字 - の最初の出現のインデックスを見つけます。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "_id":1, "name":"John Doe", "Manager":"Jane Doe", "Role":"Developer", "Desk": "Düsseldorf-BVV-021"},
  { "_id":2, "name":"John Stiles", "Manager":"Jane Doe", "Role":"Manager", "Desk": "Munich-HGG-32a"},
  { "_id":3, "name":"Richard Roe", "Manager":"Jorge Souza", "Role":"Product", "Desk": "Cologne-ayu-892.50"},
  { "_id":4, "name":"Mary Major", "Manager":"Jane Doe", "Role":"Solution Architect", "Desk": "Dortmund-Hop-78"}
])
```

**クエリの例**

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

**出力**

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

## コードの例
<a name="indexOfCP-code"></a>

`$indexOfCP` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    { $project: { stateLocation: { $indexOfCP: [ "$Desk", "-"] } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient

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

result = list(collection.aggregate([
    { '$project': { 'stateLocation': { '$indexOfCP': [ '$Desk', '-' ] } } }
]))

print(result)

client.close()
```

------

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

Amazon DocumentDB の`$indexStats`集約ステージは、コレクション内のインデックスの使用に関するインサイトを提供します。この演算子を使用すると、インデックスのアクセスパターンをモニタリングできるため、インデックスの管理と最適化について情報に基づいた意思決定を行うことができます。

**パラメータ**

なし

## 例 (MongoDB シェル)
<a name="indexStats-examples"></a>

次の例は、 `$indexStats`演算子を使用して Amazon DocumentDB コレクションのインデックス使用状況を分析する方法を示しています。

**サンプルドキュメントを作成する**

```
db.grocery.insertMany([
  { _id: 1, product: "milk", quantity: 10 },
  { _id: 2, product: "eggs", quantity: 20 },
  { _id: 3, product: "bread", quantity: 5 },
  { _id: 4, product: "cheese", quantity: 15 },
  { _id: 5, product: "apple", quantity: 8 }
]);
```

**クエリの例**

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

**出力**

```
[
  {
    "name": "_id_",
    "key": {
      "_id": 1
    },
    "host": "docdb-cluster-1.cluster-123456789.us-west-2.docdb.amazonaws.com",
    "accesses": {
      "ops": NumberLong(5),
      "since": ISODate("2023-04-06T12:34:56.789Z")
    }
  },
  {
    "name": "product_1",
    "key": {
      "product": 1
    },
    "host": "docdb-cluster-1.cluster-123456789.us-west-2.docdb.amazonaws.com",
    "accesses": {
      "ops": NumberLong(10),
      "since": ISODate("2023-04-06T12:34:56.789Z")
    }
  }
]
```

この例では、 `$indexStats`演算子は、`_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 シェル)
<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 シェル)
<a name="isoDayOfWeek-examples"></a>

次の例は、 `$isoDayOfWeek`演算子を使用して、一連のイベントドキュメントの ISO 曜日を取得する方法を示しています。

**サンプルドキュメントを作成する**

```
db.events.insertMany([
  { _id: 1, eventDate: ISODate("2023-04-01T12:00:00Z") },
  { _id: 2, eventDate: ISODate("2023-04-02T12:00:00Z") },
  { _id: 3, eventDate: ISODate("2023-04-03T12:00:00Z") },
  { _id: 4, eventDate: ISODate("2023-04-04T12:00:00Z") },
  { _id: 5, eventDate: ISODate("2023-04-05T12:00:00Z") },
  { _id: 6, eventDate: ISODate("2023-04-06T12:00:00Z") },
  { _id: 7, eventDate: ISODate("2023-04-07T12:00:00Z") }
]);
```

**クエリの例**

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

**出力**

```
[
  { "_id": 1, "eventDate": ISODate("2023-04-01T12:00:00Z"), "isoDayOfWeek": 6 },
  { "_id": 2, "eventDate": ISODate("2023-04-02T12:00:00Z"), "isoDayOfWeek": 7 },
  { "_id": 3, "eventDate": ISODate("2023-04-03T12:00:00Z"), "isoDayOfWeek": 1 },
  { "_id": 4, "eventDate": ISODate("2023-04-04T12:00:00Z"), "isoDayOfWeek": 2 },
  { "_id": 5, "eventDate": ISODate("2023-04-05T12:00:00Z"), "isoDayOfWeek": 3 },
  { "_id": 6, "eventDate": ISODate("2023-04-06T12:00:00Z"), "isoDayOfWeek": 4 },
  { "_id": 7, "eventDate": ISODate("2023-04-07T12:00:00Z"), "isoDayOfWeek": 5 }
]
```

## コードの例
<a name="isoDayOfWeek-code"></a>

`$isoDayOfWeek` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await events.aggregate([
    {
      $project: {
        _id: 1,
        eventDate: 1,
        isoDayOfWeek: { $isoDayOfWeek: '$eventDate' }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(events.aggregate([
        {
            '$project': {
                '_id': 1,
                'eventDate': 1,
                'isoDayOfWeek': { '$isoDayOfWeek': '$eventDate' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の`$isoWeek`演算子は、日付の ISO 週番号を返します。ISO 週の日付システムは、1 年の週を番号付けする方法であり、新しい年の最初の週は、その年の最初の木曜日を含む週です。これは、新年の最初の週が 1 月 1 日を含む週であるグレゴリオ暦とは異なります。

**パラメータ**

なし

## 例 (MongoDB シェル)
<a name="isoWeek-examples"></a>

次の例は、 `$isoWeek`演算子を使用して特定の日付の ISO 週番号を取得する方法を示しています。

**サンプルドキュメントを作成する**

```
db.dates.insertMany([
  { _id: 1, date: new ISODate("2022-01-01") },
  { _id: 2, date: new ISODate("2022-12-31") },
  { _id: 3, date: new ISODate("2023-01-01") }
])
```

**クエリの例**

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

**出力**

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

## コードの例
<a name="isoWeek-code"></a>

`$isoWeek` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'isoWeek': { '$isoWeek': '$date' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の`$isoWeekYear`演算子は、特定の日付の ISO 8601 週の年番号を返します。ISO の週の年番号は、特に年の開始時と終了時に、週の年が暦年と異なる場合があるという点で、グレゴリオ暦年とは異なります。

**パラメータ**
+ `expression`: ISO 8601 週の年番号を返す日付式。

## 例 (MongoDB シェル)
<a name="isoWeekYear-examples"></a>

この例では、 `$isoWeekYear`演算子を使用して、イベントコレクション内の各ドキュメントの日付フィールドの ISO 8601 週の年を取得する方法を示します。

**サンプルドキュメントを作成する**

```
db.events.insertMany([
  { _id: 1, name: "Event 1", date: ISODate("2022-12-31T00:00:00Z") },
  { _id: 2, name: "Event 2", date: ISODate("2023-01-01T00:00:00Z") },
  { _id: 3, name: "Event 3", date: ISODate("2023-01-02T00:00:00Z") }
]);
```

**クエリの例**

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

**出力**

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

## コードの例
<a name="isoWeekYear-code"></a>

`$isoWeekYear` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await events.aggregate([
    { $project: {
      name: 1,
      isoWeekYear: { $isoWeekYear: '$date' }
    }}
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(events.aggregate([
        { '$project': {
            'name': 1,
            'isoWeekYear': { '$isoWeekYear': '$date' }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の `$last`演算子は、クエリ条件に一致する配列の最後の要素を返すために使用されます。これは、特定の条件を満たす配列の最新の要素または最後の要素を取得する場合に特に便利です。

**パラメータ**
+ `expression`: 配列要素に一致する式。

## 例 (MongoDB シェル)
<a name="last-examples"></a>

次の例は、 演算子を `$last`と組み合わせて使用`$filter`して、特定の条件を満たす配列から最後の要素を取得する方法を示しています (例: subject is '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 シェル)
<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 シェル)
<a name="limit-examples"></a>

次の例は、 `$limit`演算子を使用して、指定されたフィルターに一致する最大 1 つのドキュメントを返す方法を示しています。

**サンプルドキュメントを作成する**

```
db.test.insertMany([
  { "_id": 1, "star_rating": 4, "comments": "apple is red" },
  { "_id": 2, "star_rating": 5, "comments": "comfortable couch" },
  { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" },
  { "_id": 4, "star_rating": 5, "comments": "this is a great couch" },
  { "_id": 5, "star_rating": 5, "comments": "interesting couch" }
]);
```

**クエリの例**

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

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

**出力**

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

## コードの例
<a name="limit-code"></a>

`$limit` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

      await collection.createIndex({ comments: 'text' });

      const query = {
        $and: [
          { star_rating: 5 },
          { $text: { $search: "couch" } }
        ]
      };

      const result = await collection.find(query).limit(1).toArray();

      console.log(result);

    } catch (err) {
        console.error("Error:", err);
    } finally {
        await client.close();
    }

}

limitExample();
```

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

```
from pymongo import MongoClient

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

        db = client['test']
        collection = db['test']

        collection.create_index([('comments', 'text')])

        query = {
            '$and': [
                {'star_rating': 5},
                {'$text': {'$search': 'couch'}}
            ]
        }

        result = collection.find(query).limit(1)

        for doc in result:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        client.close()

limit_example()
```

------

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

Amazon DocumentDB の `$literal`演算子は、集約パイプラインステージ内のリテラル値を表すために使用されます。これにより、フィールドリファレンスや式として解釈することなく、数値、文字列、ブール値などの特定の値を含めることができます。

この演算子は、動的クエリフィルターの構築や計算の実行など、より複雑な集計パイプラインの一部としてリテラル値を含める必要がある場合に特に便利です。

**パラメータ**

なし

## 例 (MongoDB シェル)
<a name="literal-examples"></a>

次の例は、 `$literal`演算子を使用してリテラル値を集約パイプラインに含める方法を示しています。`$literal` 演算子は、値 18 を \$1gt 式にリテラル値として含めるために使用されます。これにより、集約パイプラインは経過時間フィールドをリテラル値 18 と比較して、その人が成人かどうかを判断できます。

**サンプルドキュメントを作成する**

```
db.collection.insertMany([
  { "name": "John Doe", "age": 30, "city": "New York" },
  { "name": "Jane Doe", "age": 25, "city": "Los Angeles" },
  { "name": "Bob Smith", "age": 35, "city": "Chicago" }
]);
```

**クエリの例**

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

**出力**

```
[
  {
    "_id": ObjectId("601234567890abcdef012345"),
    "name": "John Doe",
    "age": 30,
    "city": "New York",
    "isAdult": true
  },
  {
    "_id": ObjectId("601234567890abcdef012346"),
    "name": "Jane Doe",
    "age": 25,
    "city": "Los Angeles",
    "isAdult": true
  },
  {
    "_id": ObjectId("601234567890abcdef012347"),
    "name": "Bob Smith",
    "age": 35,
    "city": "Chicago",
    "isAdult": true
  }
]
```

## コードの例
<a name="literal-code"></a>

`$literal` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        age: 1,
        city: 1,
        isAdult: { $gt: ["$age", { $literal: 18 }] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'age': 1,
                'city': 1,
                'isAdult': { '$gt': ["$age", { '$literal': 18 }] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

バージョン 4.0 の新機能。

Amazon DocumentDB の`$ln`演算子は、指定された数の自然対数 (ベース e) を計算します。数値の対数をベース e に返します。

**パラメータ**
+ `expression`: 自然対数を計算する数値。

## 例 (MongoDB シェル)
<a name="ln-examples"></a>

次の例は、`$log`演算子を使用して数値の自然対数を計算する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="ln-code"></a>

`$ln` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const db = client.db('test');
  const collection = db.collection('numbers');

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

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

example();
```

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

```
from pymongo import MongoClient

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

    db = client.test
    collection = db.numbers

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

    print(result)
    client.close()

example()
```

------

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

バージョン 4.0 の新機能。

Amazon DocumentDB の`$log`演算子は、数値の自然対数を計算します。指定された数の base-e 対数を返します。

**パラメータ**
+ `expression`: 自然対数を計算する数値。
+ `base`: ログを計算するための基本値。

## 例 (MongoDB シェル)
<a name="log-examples"></a>

次の例は、`$log`演算子を使用して数値の自然対数を計算する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="log-code"></a>

`$log` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const db = client.db('test');
  const collection = db.collection('numbers');

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

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        { "$project": {
            "_id": 1,
            "naturalLog": { "$log": ["$value", 10] }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

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

バージョン 4.0 の新機能。

Amazon DocumentDB の `$log10`演算子は、数値の base-10 対数を計算するために使用されます。集約パイプライン内の数値フィールドで対数計算を実行するのに役立ちます。

**パラメータ**
+ `expression`: base-10 対数を計算する数値式。

## 例 (MongoDB シェル)
<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` 集計演算子は 2 つの値を比較し、最初の値が 2 番目より小さい`true`場合は を返し、それ以外の場合は を返します`false`。

**パラメータ**
+ `expression1`: 比較する最初の値。
+ `expression2`: 比較する 2 番目の値。

## 例 (MongoDB シェル)
<a name="lt-aggregation-examples"></a>

次の例は、 `$lt`演算子を使用して低在庫項目を識別する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="lt-aggregation-code"></a>

`$lt` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        stock: 1,
        lowStock: { $lt: ["$stock", 10] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'stock': 1,
                'lowStock': { '$lt': ['$stock', 10] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$lte` 集計演算子は 2 つの値を比較し、最初の値が 2 番目以下の`true`場合は を返し、それ以外の場合は を返します`false`。

**パラメータ**
+ `expression1`: 比較する最初の値。
+ `expression2`: 比較する 2 番目の値。

## 例 (MongoDB シェル)
<a name="lte-aggregation-examples"></a>

次の例は、 `$lte`演算子を使用して予算にわかりやすい項目を識別する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="lte-aggregation-code"></a>

`$lte` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        dish: 1,
        price: 1,
        affordable: { $lte: ["$price", 10] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'dish': 1,
                'price': 1,
                'affordable': { '$lte': ['$price', 10] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の`$lookup`集約ステージでは、2 つのコレクション間で左外部結合を実行できます。このオペレーションでは、一致するフィールド値に基づいて、複数のコレクションのデータを組み合わせることができます。これは、関連するコレクションのデータをクエリ結果に組み込む必要がある場合に特に便利です。

**パラメータ**
+ `from`: 結合を実行するコレクションの名前。
+ `localField`: と照合する入力ドキュメントのフィールド`foreignField`。
+ `foreignField`: と照合する`from`コレクション内のドキュメントのフィールド`localField`。
+ `as`: `from`コレクションから一致するドキュメントを含む出力ドキュメントに追加する新しいフィールドの名前。

## 例 (MongoDB シェル)
<a name="lookup-examples"></a>

次の例は、`orders`コレクションから`customers`コレクションにデータを結合するシンプルな`$lookup`オペレーションを示しています。

**サンプルドキュメントを作成する**

```
db.customers.insertMany([
  { _id: 1, name: "Alice" },
  { _id: 2, name: "Bob" },
  { _id: 3, name: "Charlie" }
]);

db.orders.insertMany([
  { _id: 1, customer_id: 1, total: 50 },
  { _id: 2, customer_id: 1, total: 100 },
  { _id: 3, customer_id: 2, total: 75 }
]);
```

**クエリの例**

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

**出力**

```
[
  {
    _id: 1,
    name: 'Alice',
    orders: [
      { _id: 2, customer_id: 1, total: 100 },
      { _id: 1, customer_id: 1, total: 50 }
    ]
  },
  { _id: 3, name: 'Charlie', orders: [] },
  {
    _id: 2,
    name: 'Bob',
    orders: [ { _id: 3, customer_id: 2, total: 75 } ]
  }
]
```

## コードの例
<a name="lookup-code"></a>

`$lookup` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  await client.connect();

  const db = client.db('test');

  const result = await db.collection('customers').aggregate([
    {
      $lookup: {
        from: 'orders',
        localField: '_id',
        foreignField: 'customer_id',
        as: 'orders'
      }
    }
  ]).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

    db = client.test
    
    collection = db.customers

    pipeline = [
        {
            "$lookup": {
                "from": "orders",
                "localField": "_id",
                "foreignField": "customer_id",
                "as": "orders"
            }
        }
    ]

    result = collection.aggregate(pipeline)

    for doc in result:
        print(doc)

    client.close()

example()
```

------

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

バージョン 4.0 の新機能。

Elastic クラスターではサポートされていません。

Amazon DocumentDB の `$ltrim`演算子は、文字列から先頭文字を削除するために使用されます。デフォルトでは、先頭の空白文字は削除されますが、chars 引数を渡すことで削除する文字のセットを指定することもできます。

**パラメータ**
+ `input`: 先頭の空白文字を削除する入力文字列。
+ `chars`: (オプション) 特定の文字を削除します。

## 例 (MongoDB シェル)
<a name="ltrim-examples"></a>

次の例は、 を使用して文字列の先頭から指定された文字 (「 \$1」) `$ltrim`を削除する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

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

**出力**

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

## コードの例
<a name="ltrim-code"></a>

`$ltrim` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('collection');

    const pipeline = [
      {
        $project: {
          _id: 0,
          name: {
            $ltrim: {
              input: '$name',
              chars: ' *'
            }
          },
          age: 1
        }
      }
    ];

    const result = await collection.aggregate(pipeline).toArray();

    console.dir(result, { depth: null });

  } finally {
    await client.close();
  }
}

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

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

```
from pymongo import MongoClient

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

        db = client.test
        collection = db.collection

        pipeline = [
            {
                "$project": {
                    "_id": 0,
                    "name": {
                        "$ltrim": {
                            "input": "$name",
                            "chars": " *"
                        }
                    },
                    "age": 1
                }
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        client.close()

example()
```

------

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

Amazon DocumentDB の `$map`演算子を使用すると、配列内の各要素に指定された式を適用し、変換された要素を含む新しい配列を返すことができます。この演算子は、配列内のデータの操作と変換に特に役立ちます。これにより、配列処理をデータベースレベルにプッシュすることで、アプリケーションコードを簡素化し、クエリパフォーマンスを向上させることができます。

**パラメータ**
+ `input`: 変換する配列。
+ `as`: (オプション) 式の 内で、処理中の現在の要素を表すために使用される変数の名前。
+ `in`: 入力配列の各要素に適用される式。

## 例 (MongoDB シェル)
<a name="map-examples"></a>

次の例は、\$1map 演算子を使用して数値の配列を変換し、各値を 2 倍する方法を示しています。

**サンプルドキュメントを作成する**

```
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`パイプラインステージは、指定されたクエリ条件に一致するもののみに入力ドキュメントをフィルタリングするために使用されます。これは、集約オペレーションで最も一般的に使用されるパイプラインステージの 1 つです。`$match` ステージは他のパイプラインステージの前に適用されるため、後続のステージで処理する必要があるドキュメントの数を効率的に減らすことができます。

**パラメータ**
+ `query`: オペレーションの選択基準を表すドキュメント。クエリドキュメントは、 `find()`メソッドと同じ構文を使用します。

## 例 (MongoDB シェル)
<a name="match-examples"></a>

次の例は、 `$match`ステージを使用して、特定のフィールド値に基づいてドキュメントをフィルタリングする方法を示しています。

**サンプルドキュメントを作成する**

```
db.collection.insertMany([
  { _id: 1, name: "John", age: 25, city: "New York" },
  { _id: 2, name: "Jane", age: 30, city: "Los Angeles" },
  { _id: 3, name: "Bob", age: 35, city: "Chicago" },
  { _id: 4, name: "Alice", age: 40, city: "Miami" }
]);
```

**クエリの例**

```
db.collection.aggregate([
  { $match: { age: { $gt: 30 } } },
  { $project: { _id: 1, name: 1, city: 1 } }
]);
```

**出力**

```
[
  { "_id": 3, "name": "Bob", "city": "Chicago" },
  { "_id": 4, "name": "Alice", "city": "Miami" }
]
```

`$match` ステージは、 `age`フィールドが 30 より大きいドキュメントのみを含むようにドキュメントをフィルタリングします。

## コードの例
<a name="match-code"></a>

`$match` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.aggregate([
    { $match: { age: { $gt: 30 } } },
    { $project: { _id: 1, name: 1, city: 1 } }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        { '$match': { 'age': { '$gt': 30 } } },
        { '$project': { '_id': 1, 'name': 1, 'city': 1 } }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$max` 集約ステージは、パイプラインステージ内のすべてのドキュメントで指定されたフィールドの最大値を返すために使用されます。この演算子は、一連のドキュメントで最大値を見つけるのに役立ちます。

**パラメータ**
+ `expression`: 最大値の計算に使用する式。

## 例 (MongoDB シェル)
<a name="max-examples"></a>

次の例は、 `$max`演算子を使用して学生ドキュメントのコレクションで最大スコアを検索する方法を示しています。`$group` ステージはすべてのドキュメントをグループ化し、 `$max`演算子を使用してすべてのドキュメントの `score`フィールドの最大値を計算します。

**サンプルドキュメントを作成する**

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

**クエリの例**

```
db.students.aggregate([
  { $group: { _id: null, maxScore: { $max: "$score" } } },
  { $project: { _id: 0, maxScore: 1 } }
])
```

**出力**

```
[ { maxScore: 92 } ]
```

## コードの例
<a name="max-code"></a>

`$max` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await students.aggregate([
    { $group: { _id: null, maxScore: { $max: "$score" } } }
  ]).toArray();

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

findMaxScore();
```

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

```
from pymongo import MongoClient

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

    result = list(students.aggregate([
        { "$group": { "_id": None, "maxScore": { "$max": "$score" } } }
    ]))

    print(result)
    client.close()

find_max_score()
```

------

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

`$meta` 集約演算子は、集約パイプライン内のドキュメントに関連付けられたメタデータにアクセスします。これは一般的に、テキスト検索スコアの取得と関連性による結果のソートに使用されます。

**パラメータ**
+ `textScore`: 検索クエリへのドキュメントの関連性を示すテキスト検索スコアを取得します。

## 例 (MongoDB シェル)
<a name="meta-aggregation-examples"></a>

次の例は、集約パイプラインで `$meta`演算子を使用してテキスト検索スコアを取得およびソートする方法を示しています。

**サンプルドキュメントを作成する**

```
db.articles.createIndex({ content: "text" });

db.articles.insertMany([
  { _id: 1, title: "Python Programming", content: "Python is a versatile programming language used for web development." },
  { _id: 2, title: "Python Guide", content: "Learn Python programming with Python tutorials and Python examples." },
  { _id: 3, title: "Java Basics", content: "Java is another popular programming language." }
]);
```

**クエリの例**

```
db.articles.aggregate([
  { $match: { $text: { $search: "Python" } } },
  { $addFields: { score: { $meta: "textScore" } } },
  { $sort: { score: -1 } }
]);
```

**出力**

```
[
  {
    _id: 2,
    title: 'Python Guide',
    content: 'Learn Python programming with Python tutorials and Python examples.',
    score: 1.5
  },
  {
    _id: 1,
    title: 'Python Programming',
    content: 'Python is a versatile programming language used for web development.',
    score: 0.75
  }
]
```

## コードの例
<a name="meta-aggregation-code"></a>

`$meta` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    { $match: { $text: { $search: "Python" } } },
    { $addFields: { score: { $meta: "textScore" } } },
    { $sort: { score: -1 } }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        { '$match': { '$text': { '$search': 'Python' } } },
        { '$addFields': { 'score': { '$meta': 'textScore' } } },
        { '$sort': { 'score': -1 } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$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`: (必須) 入力ドキュメントとターゲットコレクション間の一致条件として使用するフィールド (複数可）。
+ `whenMatched`: (オプション) 入力ドキュメントがターゲットコレクション内の既存のドキュメントと一致するときに実行するアクション。サポートされている値は `"merge"`、`"replace"`、`"keepExisting"`、`"fail"` です。
+ `whenNotMatched`: (オプション) 入力ドキュメントがターゲットコレクション内のドキュメントと一致しない場合に実行するアクション。サポートされている値は、 `"insert"`と です`"fail"`。

## 例 (MongoDB シェル)
<a name="merge-examples"></a>

次の例は、 `$merge`ステージを使用して、入力パイプラインの新しいデータで`users`コレクションを更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { _id: 1, name: "John Doe", email: "john@example.com" },
  { _id: 2, name: "Jane Smith", email: "jane@example.com" }
]);

db.inputData.insertMany([
  { _id: 1, name: "John Doe", email: "john@example.com", phone: "123-456-7890" },
  { _id: 3, name: "Bob Johnson", email: "bob@example.com", phone: "987-654-3210" }
]);
```

**クエリの例**

```
db.inputData.aggregate([
  {
    $merge: {
      into: "users",
      on: "_id",
      whenMatched: "merge",
      whenNotMatched: "insert"
    }
  }
])
```

**出力**

`$merge` パイプラインを実行すると、`users`コレクションには次のドキュメントが含まれます。

```
[
  { _id: 1, name: "John Doe", email: "john@example.com", phone: "123-456-7890" },
  { _id: 2, name: "Jane Smith", email: "jane@example.com" },
  { _id: 3, name: "Bob Johnson", email: "bob@example.com", phone: "987-654-3210" }
]
```

## コードの例
<a name="merge-code"></a>

`$merge` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

Node.js アプリケーションで \$1merge 演算子を使用する例を次に示します。

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

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

  await db.collection('inputData').aggregate([
    {
      $merge: {
        into: 'users',
        on: '_id',
        whenMatched: 'merge',
        whenNotMatched: 'insert'
      }
    }
  ]).toArray();

  const users = await db.collection('users').find({}).toArray();
  console.log(users);

  await client.close();
}

example();
```

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

Python アプリケーションで \$1merge 演算子を使用する例を次に示します。

```
from pymongo import MongoClient

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

    # Assumes collections 'users' and 'inputData' already exist with sample data
    db.inputData.aggregate([
        {
            '$merge': {
                'into': 'users',
                'on': '_id',
                'whenMatched': 'merge',
                'whenNotMatched': 'insert'
            }
        }
    ])

    users = list(db.users.find({}))
    print(users)

    client.close()

example()
```

------

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

Amazon DocumentDB の `$mergeObjects`演算子は、複数のドキュメントまたはオブジェクトを 1 つのドキュメントに結合するために使用されます。この演算子は、2 つ以上のドキュメントまたはオブジェクトの内容をマージする必要があり、あるオブジェクトの値を別のオブジェクトのものと上書きする可能性がある場合に特に便利です。

**パラメータ**
+ `expression1`: マージする最初のオブジェクト。
+ `expression2`: (オプション) マージする 2 番目のオブジェクト。
+ `expression3`: (オプション) マージする追加のオブジェクト。

## 例 (MongoDB シェル)
<a name="mergeObjects-examples"></a>

次の例は、 `$mergeObjects`演算子を使用して 2 つのオブジェクトを組み合わせる方法を示しています。

**サンプルドキュメントを作成する**

```
db.collection.insertMany([
  { "_id": 1, "name": "John", "address": { "city": "New York", "state": "NY" } },
  { "_id": 2, "name": "Jane", "address": { "city": "Los Angeles", "state": "CA" } }
]);
```

**クエリの例**

```
db.collection.aggregate([
  {
    $project: {
      "combinedAddress": {
        $mergeObjects: ["$address", { "country": "USA" }]
      }
    }
  }
])
```

**出力**

```
[
  {
    "_id": 1,
    "combinedAddress": {
      "city": "New York",
      "state": "NY",
      "country": "USA"
    }
  },
  {
    "_id": 2,
    "combinedAddress": {
      "city": "Los Angeles",
      "state": "CA",
      "country": "USA"
    }
  }
]
```

## コードの例
<a name="mergeObjects-code"></a>

`$mergeObjects` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        "combinedAddress": {
          $mergeObjects: ["$address", { "country": "USA" }]
        }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                "combinedAddress": {
                    "$mergeObjects": ["$address", { "country": "USA" }]
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の `$millisecond`演算子は、日付値のミリ秒部分を抽出するために使用されます。

**パラメータ**

なし

## 例 (MongoDB シェル)
<a name="millisecond-examples"></a>

この例では、 `$millisecond`演算子を使用して日付値のミリ秒部分を抽出する方法を示します。

**サンプルドキュメントを作成する**

```
db.events.insert([
  {
    "name": "Event 1",
    "timestamp": ISODate("2023-04-21T10:30:15.123Z")
  },
  {
    "name": "Event 2",
    "timestamp": ISODate("2023-04-21T10:30:15.456Z")
  },
  {
    "name": "Event 3",
    "timestamp": ISODate("2023-04-21T10:30:15.789Z")
  }
])
```

**クエリの例**

```
db.events.aggregate([
  {
    $project: {
      name: 1,
      milliseconds: { $millisecond: "$timestamp" }
    }
  }
])
```

**出力**

```
[
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c1"),
    "name": "Event 1",
    "milliseconds": 123
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c2"),
    "name": "Event 2",
    "milliseconds": 456
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c3"),
    "name": "Event 3",
    "milliseconds": 789
  }
]
```

## コードの例
<a name="millisecond-code"></a>

`$millisecond` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await events.aggregate([
    {
      $project: {
        name: 1,
        milliseconds: { $millisecond: '$timestamp' }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient

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

result = list(events.aggregate([
    {
        '$project': {
            'name': 1,
            'milliseconds': { '$millisecond': '$timestamp' }
        }
    }
]))

print(result)

client.close()
```

------

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

`$min` 演算子は、値の配列から最小値を返します。集約ステージで使用して、複数のドキュメントで指定されたフィールドの最小値を見つけることができます。

**パラメータ**
+ `expression`: 評価する式。これは、フィールドパス、変数、または値に解決される任意の式です。

## 例 (MongoDB シェル)
<a name="min-examples"></a>

次の例は、 `$min`演算子を使用して、複数のドキュメントにわたる `age`フィールドの最小値を見つける方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

```
db.users.aggregate([
  { $group: { _id: null, minAge: { $min: "$age" } } },
  { $project: { _id: 0, minAge: 1 } }
])
```

**出力**

```
[ { minAge: 28 } ]
```

## コードの例
<a name="min-code"></a>

`$min` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await users.aggregate([
    { $group: {
        _id: null,
        minAge: { $min: "$age" }
      }}
  ]).toArray();

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

findMinAge();
```

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

```
from pymongo import MongoClient

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

    result = list(users.aggregate([
        { "$group": {
            "_id": None,
            "minAge": { "$min": "$age" }
        }}
    ]))

    print(result)
    client.close()

find_min_age()
```

------

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

Amazon DocumentDB の`$minute`集約パイプラインステージは、日付またはタイムスタンプフィールドから分値を抽出します。

この演算子は、集計パイプライン内で日付と時刻ベースの計算またはグループ化を実行する必要がある場合に便利です。

**パラメータ**
+ `expression`: 分値を抽出する日付またはタイムスタンプフィールド。

## 例 (MongoDB シェル)
<a name="minute-examples"></a>

次の例は、 `$minute`演算子を使用して、タイムスタンプフィールドから抽出された分値でドキュメントをグループ化し、各グループのドキュメントの数をカウントする方法を示しています。

**サンプルドキュメントを作成する**

```
db.events.insertMany([
  { timestamp: new Date("2023-04-15T10:30:25.000Z") },
  { timestamp: new Date("2023-04-15T10:30:35.000Z") },
  { timestamp: new Date("2023-04-15T10:31:05.000Z") },
  { timestamp: new Date("2023-04-15T10:31:45.000Z") },
  { timestamp: new Date("2023-04-15T10:32:15.000Z") }
]);
```

**クエリの例**

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

**出力**

```
[
  { "_id": { "minute": 30 }, "count": 2 },
  { "_id": { "minute": 31 }, "count": 2 },
  { "_id": { "minute": 32 }, "count": 1 }
]
```

## コードの例
<a name="minute-code"></a>

`$minute` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  await collection.insertMany([
    { timestamp: new Date("2023-04-15T10:30:25.000Z") },
    { timestamp: new Date("2023-04-15T10:30:35.000Z") },
    { timestamp: new Date("2023-04-15T10:31:05.000Z") },
    { timestamp: new Date("2023-04-15T10:31:45.000Z") },
    { timestamp: new Date("2023-04-15T10:32:15.000Z") }
  ]);

  const result = await collection.aggregate([
    {
      $group: {
        _id: {
          minute: { $minute: "$timestamp" }
        },
        count: { $count: {} }
      }
    },
    { $sort: { "_id.minute": 1 } }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient
from datetime import datetime

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

    collection.insert_many([
        {'timestamp': datetime(2023, 4, 15, 10, 30, 25)},
        {'timestamp': datetime(2023, 4, 15, 10, 30, 35)},
        {'timestamp': datetime(2023, 4, 15, 10, 31, 5)},
        {'timestamp': datetime(2023, 4, 15, 10, 31, 45)},
        {'timestamp': datetime(2023, 4, 15, 10, 32, 15)}
    ])

    result = list(collection.aggregate([
        {
            '$group': {
                '_id': {
                    'minute': {'$minute': '$timestamp'}
                },
                'count': {'$count': {}}
            }
        },
        {'$sort': {'_id.minute': 1}}
    ]))

    print(result)
    client.close()

example()
```

------

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

`$mod` 演算子は、数値に対してモジュロ演算を実行する算術演算子です。ある数値を別の数値で割った余りを返します。この演算子は、数値が奇数か偶数かを判断するため、または項目を有限数のグループに分散するために一般的に使用されます。

**パラメータ**
+ `expression1`: 分配式。
+ `expression2`: 除数式。

## 例 (MongoDB シェル)
<a name="mod-examples"></a>

この例では、 `$mod`演算子を使用して、100 個のパッケージで出荷するときに残っているウィジェットの数を確認する方法を示します。

**サンプルドキュメントを作成する**

```
db.widgets.insertMany([
  { "_id" : 1, "widget" : "A", "count" : 80372 },
  { "_id" : 2, "widget" : "B", "count" : 409282 },
  { "_id" : 3, "widget" : "C", "count" : 60739 }
])
```

**クエリの例**

```
db.widgets.aggregate([
  { $addFields: { leftOver: { $mod: [ "$count", 100 ] } } }
])
```

**出力**

```
[
  { "_id" : 1, "widget" : "A", "count" : 80372, "leftOver" : 72 },
  { "_id" : 2, "widget" : "B", "count" : 409282, "leftOver" : 82 },
  { "_id" : 3, "widget" : "C", "count" : 60739, "leftOver" : 39 }
]
```

出力には、ドキュメントごとに の残りを 100 で`count`割った値が表示されます。これは、100 個のパッケージで出荷する際の残りのウィジェットの数を表します。

## コードの例
<a name="mod-code"></a>

`$mod` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  await widgets.insertMany([
    { "_id" : 1, "widget" : "A", "count" : 80372 },
    { "_id" : 2, "widget" : "B", "count" : 409282 },
    { "_id" : 3, "widget" : "C", "count" : 60739 }
  ]);

  const result = await widgets.aggregate([
    { $addFields: { leftOver: { $mod: [ "$count", 100 ] } } }
  ]).toArray();

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

main();
```

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

```
from pymongo import MongoClient

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

widgets.insert_many([
    { "_id" : 1, "widget" : "A", "count" : 80372 },
    { "_id" : 2, "widget" : "B", "count" : 409282 },
    { "_id" : 3, "widget" : "C", "count" : 60739 }
])

result = list(widgets.aggregate([
    { "$addFields": { "leftOver": { "$mod": [ "$count", 100 ] } } }
]))

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

------

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

Amazon DocumentDB の`$month`演算子は、日付の月を 1～12 の数値として返します。この演算子は、日付フィールドから月コンポーネントを抽出し、日付ベースの集計と分析を実行するのに役立ちます。

**パラメータ**
+ `date_expression`: これは、月を抽出する日付またはタイムスタンプを含む式またはフィールドです。

## 例 (MongoDB シェル)
<a name="month-examples"></a>

次の例は、 `$month`演算子を使用して日付フィールドから月を抽出し、月別にデータをグループ化する方法を示しています。

**サンプルドキュメントを作成する**

```
db.sales.insert([
  { product: "abc123", price: 10.99, date: new Date("2022-01-15") },
  { product: "def456", price: 15.50, date: new Date("2022-02-28") },
  { product: "ghi789", price: 8.25, date: new Date("2022-03-10") },
  { product: "jkl012", price: 12.75, date: new Date("2022-04-05") },
  { product: "mno345", price: 18.99, date: new Date("2022-05-20") }
]);
```

**クエリの例**

```
db.sales.aggregate([
  { $group: { 
      _id: { month: { $month: "$date" } },
      totalSales: { $sum: "$price" }
    }},
  { $sort: { "_id.month": 1 } }
]);
```

**出力**

```
[
  { _id: { month: 1 }, totalSales: 10.99 },
  { _id: { month: 2 }, totalSales: 15.5 },
  { _id: { month: 3 }, totalSales: 8.25 },
  { _id: { month: 4 }, totalSales: 12.75 },
  { _id: { month: 5 }, totalSales: 18.99 }
]
```

## コードの例
<a name="month-code"></a>

`$month` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

    const pipeline = [
      {
        $group: {
          _id: { month: { $month: "$date" } },
          totalSales: { $sum: "$price" }
        }
      },
      {
        $sort: { "_id.month": 1 }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();

    console.dir(results, { depth: null });

  } finally {
    await client.close();
  }
}

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

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

```
from pymongo import MongoClient

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

    try:
        db = client.test
        collection = db.sales

        pipeline = [
            {
                "$group": {
                    "_id": { "$month": "$date" }, 
                    "totalSales": { "$sum": "$price" }  
                }
            },
            {
                "$sort": { "_id": 1 } 
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        client.close()

group_sales_by_month()
```

------

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

Amazon DocumentDB の `$multiply`演算子は、2 つ以上のフィールドまたは式の値を乗算するために使用されます。この演算子は、ドキュメント内の数値フィールドに対して算術演算を実行する場合に特に便利です。`$project` や など、集約パイプラインのさまざまな段階で使用して、新しいフィールドを作成したり`$addFields`、既存のフィールドを変更したりできます。

**パラメータ**
+ `expression1`: 乗算する最初の数値式。
+ `expression2`: 乗算する 2 番目の数値式。
+ `[expression3, ...]`: (オプション) 乗算する追加の数値式。

## 例 (MongoDB シェル)
<a name="multiply-examples"></a>

次の例では`$multiply`、 を使用して、旅行`bonus_rate`にクレジットカードを使用したお客様の `base_miles`と を乗算`bonus_miles`して計算する方法を示します。

**サンプルドキュメント**

```
db.miles.insertMany([
{ "_id": 1, "customer_name": "Arnav Desai", "member_since": ISODate("1997-03-01T00:00:00Z"), "base_miles": 2500, "bonus_rate": 1.8, "credit_card": true, "trip_cost": 250 },
{ "_id": 2, "customer_name": "Jorge Souza", "member_since": ISODate("2004-01-10T00:00:00Z"), "base_miles": 1890, "bonus_rate": 1.4, "credit_card": true, "trip_cost": 189 },
{ "_id": 3, "customer_name": "Saanvi Sarkar", "member_since": ISODate("1999-11-22T00:00:00Z"), "base_miles": 3250, "bonus_rate": 1.8, "credit_card": false, "trip_cost": 325 },
{ "_id": 4, "customer_name": "Paulo Santos", "member_since": ISODate("2021-06-19T00:00:00Z"), "base_miles": 2980, "bonus_rate": 1.2, "credit_card": true, "trip_cost": 298 },
{ "_id": 5, "customer_name": "Wang Xiulan", "member_since": ISODate("1995-12-04T00:00:00Z"), "base_miles": 1350, "bonus_rate": 1.9, "credit_card": false, "trip_cost": 135 }
]);
```

**クエリの例**

```
db.miles.aggregate([
  {
    $match: { credit_card: true }
  },
  {
    $project: {
      customer_name: 1,
      base_miles: 1,
      bonus_rate:1,
      credit_card: 1,
      total_miles: {
        $multiply: ["$base_miles", "$bonus_rate"]
      }
    }
  }
]);
```

**出力**

```
[
  { _id: 1, customer_name: 'Arnav Desai', base_miles: 12500, bonus_rate: 1.8, credit_card: true, total_miles: 22500 },
  { _id: 3, customer_name: 'Saanvi Sarkar',base_miles: 15200, bonus_rate: 1.8, credit_card: true, total_miles: 27360 },
  { _id: 4, customer_name: 'Paulo Santos', base_miles: 3400, bonus_rate: 1.1, credit_card: true, total_miles: 3740 }
]
```

## コードの例
<a name="multiply-code"></a>

`$multiply` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    { $match: { credit_card: true } },
    {
      $project: {
        customer_name: 1,
        base_miles: 1,
        bonus_rate: 1,
        credit_card: 1,
        total_miles: {
          $multiply: ["$base_miles", "$bonus_rate"]
        }
      }
    }
  ]).toArray();

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

multiplyBonusMiles();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {'$match': {'credit_card': True}},
        {
            '$project': {
                'customer_name': 1,
                'base_miles': 1,
                'bonus_rate': 1,
                'credit_card': 1,
                'total_miles': {
                    '$multiply': ['$base_miles', '$bonus_rate']
                }
            }
        }
    ]))

    print(result)
    client.close()

multiply_bonus_miles()
```

------

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

Amazon DocumentDB の `$natural`演算子は、ドキュメントを自然な順序でソートするために使用されます。これは、ドキュメントがコレクションに挿入された順序です。これは、デフォルトのソート動作とは対照的です。これは、指定されたフィールドの値に基づいてドキュメントをソートすることです。

**パラメータ**

なし

## 例 (MongoDB シェル)
<a name="natural-examples"></a>

次の例は、 `$natural`演算子を使用してコレクション内のドキュメントを自然な順序でソートする方法を示しています。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "_id": 1, "name": "María García", "age": 28 },
  { "_id": 2, "name": "Arnav Desai", "age": 32 },
  { "_id": 3, "name": "Li Juan", "age": 25 },
  { "_id": 4, "name": "Carlos Salazar", "age": 41 },
  { "_id": 5, "name": "Sofia Martínez", "age": 35 }
]);
```

**クエリの例**

```
db.people.find({}, { "_id": 1, "name": 1 }).sort({ "$natural": 1 });
```

**出力**

```
[
  { "_id": 1, "name": "María García" },
  { "_id": 2, "name": "Arnav Desai" },
  { "_id": 3, "name": "Li Juan" },
  { "_id": 4, "name": "Carlos Salazar" },
  { "_id": 5, "name": "Sofia Martínez" }
]
```

クエリは、コレクション内のドキュメントを自然な順序でソートします。これは、挿入された順序です。

## コードの例
<a name="natural-code"></a>

`$natural` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const documents = await collection.find({}, { projection: { _id: 1, name: 1 } })
    .sort({ $natural: 1 })
    .toArray();

  console.log(documents);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

    documents = list(collection.find({}, {'_id': 1, 'name': 1}).sort('$natural', 1))
    print(documents)

    client.close()

example()
```

------

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

`$ne` 集計演算子は 2 つの値を比較し、等しく`true`ない場合は を返し、等しくない場合は を返します`false`。

**パラメータ**
+ `expression1`: 比較する最初の値。
+ `expression2`: 比較する 2 番目の値。

## 例 (MongoDB シェル)
<a name="ne-aggregation-examples"></a>

次の例は、 `$ne`演算子を使用してステータスが変更された注文を識別する方法を示しています。

**サンプルドキュメントを作成する**

```
db.orders.insertMany([
  { _id: 1, orderId: "A123", status: "shipped", expectedStatus: "shipped" },
  { _id: 2, orderId: "B456", status: "pending", expectedStatus: "shipped" },
  { _id: 3, orderId: "C789", status: "delivered", expectedStatus: "delivered" }
]);
```

**クエリの例**

```
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      status: 1,
      expectedStatus: 1,
      needsAttention: { $ne: ["$status", "$expectedStatus"] }
    }
  }
]);
```

**出力**

```
[
  { _id: 1, orderId: 'A123', status: 'shipped', expectedStatus: 'shipped', needsAttention: false },
  { _id: 2, orderId: 'B456', status: 'pending', expectedStatus: 'shipped', needsAttention: true },
  { _id: 3, orderId: 'C789', status: 'delivered', expectedStatus: 'delivered', needsAttention: false }
]
```

## コードの例
<a name="ne-aggregation-code"></a>

`$ne` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        orderId: 1,
        status: 1,
        expectedStatus: 1,
        needsAttention: { $ne: ["$status", "$expectedStatus"] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'orderId': 1,
                'status': 1,
                'expectedStatus': 1,
                'needsAttention': { '$ne': ['$status', '$expectedStatus'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$not` 集計演算子は、式に対して論理 NOT オペレーションを実行します。これは、式が に評価`true`された場合と`false`、式が に評価`false`された場合を返します`true`。

**パラメータ**
+ `expression`: 否定する式。

## 例 (MongoDB シェル)
<a name="not-aggregation-examples"></a>

次の例は、 `$not`演算子を使用してブール値を反転させる方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { _id: 1, name: "Alice", active: true },
  { _id: 2, name: "Bob", active: false },
  { _id: 3, name: "Charlie", active: true }
]);
```

**クエリの例**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      active: 1,
      inactive: { $not: ["$active"] }
    }
  }
]);
```

**出力**

```
[
  { _id: 1, name: 'Alice', active: true, inactive: false },
  { _id: 2, name: 'Bob', active: false, inactive: true },
  { _id: 3, name: 'Charlie', active: true, inactive: false }
]
```

## コードの例
<a name="not-aggregation-code"></a>

`$not` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        active: 1,
        inactive: { $not: ["$active"] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'active': 1,
                'inactive': { '$not': ['$active'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の`$objectToArray`集計演算子は、オブジェクト (またはドキュメント) を配列に変換します。演算子への入力はドキュメントであり、出力は入力ドキュメント内の各フィールドと値のペアの配列要素で構成されます。この演算子は、特定のフィールドの最大値または最小値を持つドキュメントを検索する場合など、ドキュメントの個々のフィールドを配列として操作する必要がある場合に便利です。

**パラメータ**
+ `expression`: 配列に変換するドキュメント式。

## 例 (MongoDB シェル)
<a name="objectToArray-examples"></a>

次の例は、 `$objectToArray`演算子を使用して、ビデオレンタルストアチェーンの最大インベントリを持つドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

```
db.videos.aggregate([
  {
    $project: {
      name: 1,
      videos: {
        $objectToArray: "$inventory"
      }
    }
  },
  {
    $unwind: "$videos"
  },
  {
    $group: {
      _id: "$name",
      maxInventory: {
        $max: "$videos.v"
      }
    }
  }
]);
```

**出力**

```
[
  {
    "_id": "Bravemind",
    "maxInventory": 1000
  },
  {
    "_id": "Live Soft",
    "maxInventory": 1000
  },
  {
    "_id": "Romancing the Rock",
    "maxInventory": 500
  },
  {
    "_id": "Top Pilot",
    "maxInventory": 1000
  }
]
```

## コードの例
<a name="objectToArray-code"></a>

`$objectToArray` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await videos.aggregate([
    {
      $project: {
        name: 1,
        videos: {
          $objectToArray: "$inventory"
        }
      }
    },
    {
      $unwind: "$videos"
    },
    {
      $group: {
        _id: "$name",
        maxInventory: {
          $max: "$videos.v"
        }
      }
    }
  ]).toArray();

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

findMaxInventory();
```

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

```
from pymongo import MongoClient

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

    result = list(videos.aggregate([
        {
            '$project': {
                'name': 1,
                'videos': {
                    '$objectToArray': '$inventory'
                }
            }
        },
        {
            '$unwind': '$videos'
        },
        {
            '$group': {
                '_id': '$name',
                'maxInventory': {
                    '$max': '$videos.v'
                }
            }
        }
    ]))

    print(result)
    client.close()

find_max_inventory()
```

------

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

`$or` 集計演算子は複数の式を評価し、少なくとも 1 つの式が に評価`true`された場合に を返します`true`。すべての式が である`false`場合にのみ返されます`false`。

**パラメータ**
+ `expressions`: 評価する式の配列。

## 例 (MongoDB シェル)
<a name="or-aggregation-examples"></a>

次の例では、 `$or`演算子を使用して、製品が複数の条件のいずれかを満たしているかどうかを確認します。

**サンプルドキュメントを作成する**

```
db.items.insertMany([
  { _id: 1, name: "Widget", price: 150, onSale: false },
  { _id: 2, name: "Gadget", price: 45, onSale: false },
  { _id: 3, name: "Tool", price: 200, onSale: true }
]);
```

**クエリの例**

```
db.items.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      onSale: 1,
      goodDeal: {
        $or: [
          { $lt: ["$price", 50] },
          { $eq: ["$onSale", true] }
        ]
      }
    }
  }
]);
```

**出力**

```
[
  { _id: 1, name: 'Widget', price: 150, onSale: false, goodDeal: false },
  { _id: 2, name: 'Gadget', price: 45, onSale: false, goodDeal: true },
  { _id: 3, name: 'Tool', price: 200, onSale: true, goodDeal: true }
]
```

## コードの例
<a name="or-aggregation-code"></a>

`$or` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        price: 1,
        onSale: 1,
        goodDeal: {
          $or: [
            { $lt: ["$price", 50] },
            { $eq: ["$onSale", true] }
          ]
        }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'price': 1,
                'onSale': 1,
                'goodDeal': {
                    '$or': [
                        { '$lt': ['$price', 50] },
                        { '$eq': ['$onSale', True] }
                    ]
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の `$out`演算子は、集約パイプラインの結果を指定されたコレクションに書き込むために使用されます。

`$out` はパイプラインの最後のステージである必要があります。

**パラメータ**
+ `output_collection`: 集計結果を書き込む出力コレクションの名前。

**注**: コレクションが既に存在する場合、集約ステージの結果に置き換えられます。

## 例 (MongoDB シェル)
<a name="out-examples"></a>

次の例は、Amazon DocumentDB の `$out`演算子を使用して、集約パイプラインの結果を新しいコレクションに書き込む方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertMany([
  { _id: 1, name: "Wireless Headphones", category: "Electronics", price: 100.0 },
  { _id: 2, name: "Smartphone", category: "Electronics", price: 200.0 },
  { _id: 3, name: "JavaScript Guide", category: "Books", price: 50.0 },
  { _id: 4, name: "Database Design Handbook", category: "Books", price: 75.0 }
]);
```

**クエリの例**

```
db.products.aggregate([
  { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
  { $out: "product_categories" }
])
```

**出力**

なし (結果は出力コレクションに書き込まれます）。

集約パイプラインは製品をカテゴリ別にグループ化し、各カテゴリの項目の合計価格を計算します。`$out` 演算子は、「product\$1categories」という名前の新しいコレクションに結果を書き込みます。

**出力コレクションで結果を表示するには:**

```
db.product_categories.find()
[
{ "_id" : "Books", "totalPrice" : 125 },
{ "_id" : "Electronics", "totalPrice" : 300 }
]
```

## コードの例
<a name="out-code"></a>

`$out` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  // Execute aggregation with $out - results are stored in 'product_categories' collection
  await products.aggregate([
    { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
    { $out: "product_categories" }
  ]).toArray();

  // Retrieve the results from the output collection (limited to 20 records)
  const productCategories = db.collection('product_categories');
  const results = await productCategories.find({}).limit(20).toArray();
  
  console.log('Results stored in product_categories collection:', results);
  await client.close();
}

demo_out_operator();
```

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

```
from pymongo import MongoClient

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

    # Execute aggregation with $out - results are stored in 'product_categories' collection
    list(products.aggregate([
        { '$group': { '_id': '$category', 'totalPrice': { '$sum': '$price' } } },
        { '$out': 'product_categories' }
    ]))

    # Retrieve the results from the output collection (limited to 20 records)
    product_categories = db['product_categories']
    results = list(product_categories.find({}).limit(20))
    
    print('Results stored in product_categories collection:', results)
    client.close()

demo_out_operator()
```

------

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

8.0 で導入

Amazon DocumentDB の `$pow`演算子を使用すると、数値をパワーに上げることができます。これは、集約パイプライン内で指数計算を実行するのに役立ちます。

**パラメータ**
+ `<number>` (必須): 電力に引き上げる数値。
+ `<exponent>` (必須): 数値を上げるべき電力。

## 例 (MongoDB シェル)
<a name="pow-examples"></a>

次の例は、 `$pow`演算子を使用して数値の二乗を計算する方法を示しています。

**サンプルドキュメントを作成する**

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

**クエリの例**

```
db.numbers.aggregate([
  { $addFields: { "square": { $pow: ["$value", 2] } } }
])
```

**出力**

```
[
  { "_id": 1, "value": 2, "square": 4 },
  { "_id": 2, "value": 3, "square": 9 },
  { "_id": 3, "value": 4, "square": 16 }
]
```

## コードの例
<a name="pow-code"></a>

`$pow` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

Node.js アプリケーションで \$1pow 演算子を使用する例を次に示します。

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

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

  const result = await collection.aggregate([
    { $addFields: { "square": { $pow: ["$value", 2] } } }
  ]).toArray();

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

example();
```

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

Python アプリケーションで \$1pow 演算子を使用する例を次に示します。

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        { "$addFields": { "square": { "$pow": ["$value", 2] } } }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$push` 集計演算子は、各グループの指定された式からすべての値の配列を返します。これは通常、値を配列に蓄積するために`$group`ステージ内で使用されます。

**パラメータ**
+ `expression`: グループ内の各ドキュメントについて評価する式。

## 例 (MongoDB シェル)
<a name="push-aggregation-examples"></a>

次の例は、 `$push`演算子を使用して各カテゴリのすべての製品名を収集する方法を示しています。

**サンプルドキュメントを作成する**

```
db.sales.insertMany([
  { _id: 1, category: "Electronics", product: "Laptop", amount: 1200 },
  { _id: 2, category: "Electronics", product: "Mouse", amount: 25 },
  { _id: 3, category: "Furniture", product: "Desk", amount: 350 },
  { _id: 4, category: "Furniture", product: "Chair", amount: 150 },
  { _id: 5, category: "Electronics", product: "Keyboard", amount: 75 }
]);
```

**クエリの例**

```
db.sales.aggregate([
  {
    $group: {
      _id: "$category",
      products: { $push: "$product" }
    }
  }
]);
```

**出力**

```
[
  { _id: 'Furniture', products: [ 'Desk', 'Chair' ] },
  { _id: 'Electronics', products: [ 'Laptop', 'Mouse', 'Keyboard' ] }
]
```

## コードの例
<a name="push-aggregation-code"></a>

`$push` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $group: {
        _id: "$category",
        products: { $push: "$product" }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$group': {
                '_id': '$category',
                'products': { '$push': '$product' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の `$project`演算子を使用すると、出力ドキュメントにフィールドを選択的に含めたり除外したり、値を次のパイプラインステージに渡したり、入力ドキュメント値から新しいフィールドを計算したりできます。

**パラメータ**
+ `field`: 出力ドキュメントに含めるか除外するフィールドは、フィールドパス (例：「a.b.c」) にすることができます。
+ `1` または `true`: 出力に フィールドが含まれます。
+ `0` または `false`: 出力から フィールドを除外します。

## 例 (MongoDB シェル)
<a name="project-examples"></a>

次の例は、学生コレクションでの `$project`演算子の使用を示しています。

**サンプルドキュメントを作成する**

```
db.students.insertMany([
  { "_id": 1, "name": "Alejandro Rosalez", "math": 85, "science": 92, "grade": "A" },
  { "_id": 2, "name": "Carlos Salazar", "math": 78, "science": 84, "grade": "B" },
  { "_id": 3, "name": "Nikhil Jayashankar", "math": 95, "science": 89, "grade": "A" },
  { "_id": 4, "name": "Shirley Rodriguez", "math": 72, "science": 76, "grade": "B" }
  ]);
```

このクエリには、出力の フィールド`name`と `math`フィールドのみが含まれます。`_id` フィールドは、明示的に除外されない限り、デフォルトで含まれます。

```
db.students.aggregate([
  { $project: { "name": 1, "math": 1 } }
])
```

**出力**

```
{ _id: 1, name: "Alejandro Rosalez", math: 85 }
{ _id: 2, name: "Carlos Salazar", math: 78 }
{ _id: 3, name: "Nikhil Jayashankar", math: 95 }
{ _id: 4, name: "Shirley Rodriguez", math: 72 }
```

このクエリでは、 `grade`および `_id`フィールドが出力から除外され、他のすべてのフィールド (`name`、`math`、) が表示されます`science`。

```
db.students.aggregate([
  { $project: { "grade": 0, "_id": 0 } }
])
```

**出力**

```
{ name: "Alejandro Rosalez", math: 85, science: 92 }
{ name: "Carlos Salazar", math: 78, science: 84 }
{ name: "Nikhil Jayashankar", math: 95, science: 89 }
{ name: "Shirley Rodriguez", math: 72, science: 76 }
```

## コードの例
<a name="project-code"></a>

`$project` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    { $project: { "name": 1, "math": 1 } }
  ]).toArray();
  console.log(result);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        { '$project': { 'name': 1, 'math': 1 } }
    ]))
    print(result)

    client.close()

example()
```

------

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

バージョン 8.0 の新機能

Amazon DocumentDB の `$rand`演算子は、0～1 の乱数を生成するために使用されます。

**パラメータ**

なし

## 例 (MongoDB シェル)
<a name="rand-examples"></a>

次の例は、 `$rand`演算子を使用して`temp`コレクションから 2 つのドキュメントをランダムに選択する方法を示しています。

**サンプルドキュメントを作成する**

```
db.items.insertMany([
  { "name": "pencil", "quantity": 110 },
  { "name": "pen", "quantity": 159 }
])
```

**クエリの例**

```
db.items.aggregate([
  {
    $project: {
      randomValue: { $rand: {} }
    }
  }
])
```

**出力**

```
[
  {
    _id: ObjectId('6924a5edd66dcae121d29517'),
    randomValue: 0.8615243955294392
  },
  {
    _id: ObjectId('6924a5edd66dcae121d29518'),
    randomValue: 0.22815483022099903
  }
]
```

## コードの例
<a name="rand-code"></a>

`$rand` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

  console.log(result);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

  result = list(collection.aggregate([
      {
        "$project": {
          "randomValue": { "$rand": {} }
        }
      }
  ]))

  print(result)

  client.close()

example()
```

------

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

Amazon DocumentDB の`$range`集計演算子は、指定された範囲内の連続した数値の配列を作成するために使用されます。この演算子は、以下の例に示すように、レースの補助ステーションのマイルマーカーなど、一連の数値を生成するのに特に便利です。

**パラメータ**
+ `start`: 範囲の開始値。
+ `end`: 範囲の終了値。
+ `step`: (オプション) 範囲の生成時に使用するステップ値。指定しない場合、デフォルトのステップ値は 1 です。

## 例 (MongoDB シェル)
<a name="range-examples"></a>

この例では、 `$range`演算子を使用して、自転車レースのウォーターステーションのマイルマーカーを生成します。

**サンプルドキュメントを作成する**

```
db.races.insertMany([
  { _id: 0, race: "STP", distance: 206 },
  { _id: 1, race: "RSVP", distance: 160 },
  { _id: 2, race: "Chilly Hilly", distance: 33 },
  { _id: 3, race: "Flying Wheels", distance: 100 }
]);
```

**クエリの例**

```
db.races.aggregate([
  {
    $project: {
      race: 1,
      "waterStations": { $range: [20, "$distance", 20] }
    }
  }
]);
```

**出力**

```
[
  {
    _id: 0,
    race: 'STP',
    waterStations: [
       20,  40,  60,  80,
      100, 120, 140, 160,
      180, 200
    ]
  },
  {
    _id: 1,
    race: 'RSVP',
    waterStations: [
       20,  40,  60, 80,
      100, 120, 140
    ]
  },
  { _id: 2, race: 'Chilly Hilly', waterStations: [ 20 ] },
  { _id: 3, race: 'Flying Wheels', waterStations: [ 20, 40, 60, 80 ] }
]
```

## コードの例
<a name="range-code"></a>

`$range` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

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

    const pipeline = [
      {
        $project: {
          race: 1,
          waterStations: { $range: [20, "$distance", 20] } 
        }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();

    console.dir(results, { depth: null });

  } finally {
    await client.close();
  }
}

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

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

```
from pymongo import MongoClient

def example():

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

  try:
      db = client.test
      collection = db.races

      pipeline = [
          {
              "$project": {
                  "race": 1,
                  "waterStations": { "$range": [20, "$distance", 20] }
              }
          }
      ]

      results = collection.aggregate(pipeline)

      for doc in results:
          print(doc)

  except Exception as e:
      print(f"An error occurred: {e}")

  finally:
      client.close()

example()
```

------

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

Amazon DocumentDB の`$redact`集約ステージは、指定されたフィールドの値に基づいて出力ドキュメントにコンテンツを選択的に含めたり除外したりするために使用します。これは、アクセスレベルまたはユーザーのアクセス許可に基づいて機密データの可視性を制御する必要があるシナリオで特に役立ちます。

**パラメータ**
+ `$cond`: ドキュメント内の各フィールド`$$DESCEND`について、`$$KEEP`、`$$PRUNE`、または のいずれかに評価される式。
+ `$$KEEP`: 出力ドキュメントの現在のフィールドを保持します。
+ `$$PRUNE`: 出力ドキュメントから現在のフィールドを削除します。
+ `$$DESCEND`: オブジェクトまたは配列である現在のフィールドに`$redact`ステージを再帰的に適用します。

## 例 (MongoDB シェル)
<a name="redact-examples"></a>

この例では、ステージを使用してステータスに基づいて注文をフィルタリング`$redact`し、特定のステータス値を持つ注文のみを表示します。

**サンプルドキュメントを作成する**

```
db.orders.insert([
  { "_id": 1, "status": "shipped", "customer": "Carlos Salazar", "total": 150.00, "date": "2025-01-15" },
  { "_id": 2, "status": "processing", "customer": "Saanvi Sarkar", "total": 89.99, "date": "2025-01-20" },
  { "_id": 3, "status": "cancelled", "customer": "Zhang Wei", "total": 220.50, "date": "2025-01-18" }
])
```

**クエリの例**

```
db.orders.aggregate([
  {
    $redact: {
      $cond: {
        if: { $in: ["$status", ["shipped", "processing"]] },
        then: "$$KEEP",
        else: "$$PRUNE"
      }
    }
  }
])
```

**出力**

```
[
  { _id: 1, status: 'shipped', customer: 'Carlos Salazar', total: 150, date: '2025-01-15' },
  { _id: 2, status: 'processing', customer: 'Saanvi Sarkar', total: 89.99, date: '2025-01-20' }
]
```

この例では、`$redact`ステージは各ドキュメントの `status`フィールドの値をチェックします。`status` が「出荷済み」または「処理中」の場合、ドキュメントは保持されます (`$$KEEP`)。それ以外の場合、ドキュメントはプルーニングされます (`$$PRUNE`)。

## コードの例
<a name="redact-code"></a>

`$redact` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $redact: {
        $cond: {
          if: { $in: ['$status', ['shipped', 'processing']] },
          then: '$$KEEP',
          else: '$$PRUNE'
        }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$redact': {
                '$cond': {
                    'if': { '$in': ['$status', ['shipped', 'processing']] },
                    'then': '$$KEEP',
                    'else': '$$PRUNE'
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB の`$reduce`集計演算子は、配列の要素に 2 つの引数の関数を累積的に適用して、配列を 1 つの値に減らすために使用されます。この演算子は、集計パイプライン内の配列データに対して複雑な計算または変換を実行する場合に特に便利です。

**パラメータ**
+ `input`: 削減する配列。
+ `initialValue`: 削減オペレーションで使用される初期値。
+ `in`: `input`配列の各要素で評価される式。この式は、次のリダクションの反復で使用される値を返す必要があります。

## 例 (MongoDB シェル)
<a name="reduce-examples"></a>

次の例は、 `$reduce`演算子を使用して配列内のすべての要素の合計を計算する方法を示しています。

**サンプルドキュメントを作成する**

```
db.orders.insertMany([
  { "_id": 1, "items": [1, 2, 3, 4, 5] },
  { "_id": 2, "items": [10, 20, 30] },
  { "_id": 3, "items": [5, 15, 25, 35] },
  { "_id": 4, "items": [100, 200] }
])
```

**クエリの例**

```
db.orders.aggregate([
  {
    $project: {
      total: {
        $reduce: {
          input: "$items",
          initialValue: 0,
          in: { $add: ["$$value", "$$this"] }
        }
      }
    }
  }
])
```

**出力**

```
[
  { "_id": 1, "total": 15 },
  { "_id": 2, "total": 60 },
  { "_id": 3, "total": 80 },
  { "_id": 4, "total": 300 }
]
```

`$reduce` 演算子は`items`配列を繰り返し、各要素を 0 `initialValue`の に追加します。結果は、配列内のすべての要素の合計です。

## コードの例
<a name="reduce-code"></a>

`$reduce` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

Node.js アプリケーションで `$reduce`演算子を使用する例を次に示します。

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

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

  const result = await orders.aggregate([
    {
      $project: {
        total: {
          $reduce: {
            input: "$items",
            initialValue: 0,
            in: { $add: ["$$value", "$$this"] }
          }
        }
      }
    }
  ]).toArray();

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

main();
```

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

Python アプリケーションで `$reduce`演算子を使用する例を次に示します。

```
from pymongo import MongoClient

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

    result = list(orders.aggregate([
        {
            "$project": {
                "total": {
                    "$reduce": {
                        "input": "$items",
                        "initialValue": 0,
                        "in": { "$add": ["$$value", "$$this"] }
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

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

------

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

バージョン 5.0 の新機能。

Elastic クラスターではサポートされていません。

Amazon DocumentDB の `$regexFind`演算子は、ドキュメント内の文字列フィールドで正規表現マッチングを実行するために使用されます。これにより、特定の正規表現パターンに一致する特定の部分文字列を検索して抽出できます。

**パラメータ**
+ `input`: 検索する文字列フィールドまたは式。
+ `regex`: 一致する正規表現パターン。
+ `options`: (オプション) 大文字と小文字の区別や複数行の一致など、正規表現のオプションパラメータを指定するオブジェクト。サポートされているオプションは、 `i` (大文字と小文字を区別しない) と `m` (複数行) です。

## 例 (MongoDB シェル)
<a name="regexFind-examples"></a>

次の例は、 `$regexFind`演算子を使用して、 `name`フィールドが特定の正規表現パターンに一致するドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { "_id": 1, name: "John Doe", email: "john@example.com" },
  { "_id": 2, name: "Diego Ramirez", email: "diego@example.com" },
  { "_id": 3, name: "Alejandro Rosalez", email: "alejandro@example.com" },
  { "_id": 4, name: "Shirley Rodriguez", email: "shirley@example.com" }
]);
```

**クエリの例**

```
db.users.aggregate([
  {
    $project: {
      names: {
        $regexFind: { input: '$name', regex: 'j', options: 'i' }
      }
    }
  },
  { $match: {names: {$ne: null}}}
])
```

このクエリは、 `name`フィールドに「j」という文字が含まれているすべてのドキュメントを返します (大文字と小文字は区別されません）。

**出力**

```
[
  { _id: 1, names: { match: 'J', idx: 0, captures: [] } }
]
```

**注:** クエリで Amazon DocumentDB プランナーバージョン 1 を使用している場合は、ヒントを使用してインデックスを使用する必要があります。ヒントがない場合、クエリはコレクションスキャンを実行する場合があります。プランナーのバージョンを確認し、ヒントの使用の詳細については、「[Amazon DocumentDB クエリプランナードキュメント](https://docs.aws.amazon.com/documentdb/latest/developerguide/query-planner.html)」を参照してください。

## コードの例
<a name="regexFind-code"></a>

`$regexFind` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const results = await users.aggregate([
    { $project: { names: { $regexFind: { input: "$name", regex: "john", options: "i" }}}},
    { $match: {names: {$ne: null}}}
  ]).toArray();
  

  console.log(results);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient

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

results = list(users.aggregate([
    { "$project": { "names": { "$regexFind": { "input": "$name", "regex": "john", "options": "i" }}}},
    { "$match": {"names": {"$ne": None}}}
]))

print(results)

client.close()
```

------

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

5.0 で導入

Amazon DocumentDB の `$regexFindAll`演算子は、ドキュメント内の文字列フィールドで正規表現マッチングを実行するために使用されます。これにより、特定の正規表現パターンに一致する特定の部分文字列を検索して抽出し、正規表現のすべての一致を返すことができます。

**パラメータ**
+ `input`: 検索する文字列フィールドまたは式。
+ `regex`: 一致する正規表現パターン。
+ `options`: (オプション) 大文字と小文字の区別や複数行の一致など、正規表現のオプションパラメータを指定するオブジェクト。サポートされているオプションは、 `i` (大文字と小文字を区別しない) と `m` (複数行) です。

## 例 (MongoDB シェル)
<a name="regexFindAll-examples"></a>

次の例は、 `$regexFindAll`演算子を使用して `email`フィールドからすべての文字シーケンスを抽出する方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { _id: 1, name: "John Doe", email: "john@example.com", phone: "555-1234" },
  { _id: 2, name: "Jane Roe", email: "jane@example.com", phone: "555-5678" },
  { _id: 3, name: "Carlos Salazar", email: "carlos@example.com", phone: "555-3456" },
  { _id: 4, name: "Saanvi Sarkar", email: "saanvi@example.com", phone: "555-7890" }
  
]);
```

**クエリの例**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      emailMatches: {
        $regexFindAll: { input: '$email', regex: '[a-z]+', options: 'i' }
      }
    }
  }
])
```

**出力**

```
[
  {
    _id: 1,
    name: 'John Doe',
    emailMatches: [
      { match: 'john', idx: 0, captures: [] },
      { match: 'example', idx: 5, captures: [] },
      { match: 'com', idx: 13, captures: [] }
    ]
  },
  {
    _id: 2,
    name: 'Jane Roe',
    emailMatches: [
      { match: 'jane', idx: 0, captures: [] },
      { match: 'example', idx: 5, captures: [] },
      { match: 'com', idx: 13, captures: [] }
    ]
  },
  {
    _id: 3,
    name: 'Carlos Salazar',
    emailMatches: [
      { match: 'carlos', idx: 0, captures: [] },
      { match: 'example', idx: 7, captures: [] },
      { match: 'com', idx: 15, captures: [] }
    ]
  },
  {
    _id: 4,
    name: 'Saanvi Sarkar',
    emailMatches: [
      { match: 'saanvi', idx: 0, captures: [] },
      { match: 'example', idx: 7, captures: [] },
      { match: 'com', idx: 15, captures: [] }
    ]
  }
]
```

**注:** クエリで Amazon DocumentDB プランナーバージョン 1 を使用している場合は、ヒントを使用してインデックスを使用する必要があります。ヒントがない場合、クエリはコレクションスキャンを実行する場合があります。プランナーのバージョンを確認し、ヒントの使用の詳細については、「[Amazon DocumentDB クエリプランナードキュメント](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 シェル)
<a name="regexMatch-examples"></a>

次の例は、 `$regexMatch`演算子を使用して、名前が文字「M」で始まるかどうかを確認する方法を示しています。演算子は、ドキュメント`false`ごとに `true`または を返します。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { "_id":1, name: "María García", email: "maría@example.com" },
  { "_id":2, name: "Arnav Desai", email: "arnav@example.com" },
  { "_id":3, name: "Martha Rivera", email: "martha@example.com" },
  { "_id":4, name: "Richard Roe", email: "richard@example.com" },

]);
```

**クエリの例**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      startsWithM: {
        $regexMatch: {
          input: "$name",
          regex: "^M",
          options: "i"
        }
      }
    }
  }
]);
```

**出力**

```
{ _id: 1, name: 'María García', startsWithM: true },
{ _id: 2, name: 'Arnav Desai', startsWithM: false },
{ _id: 3, name: 'Martha Rivera', startsWithM: true },
{ _id: 4, name: 'Richard Roe', startsWithM: false }
```

## コードの例
<a name="regexMatch-code"></a>

`$regexMatch` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        startsWithM: {
          $regexMatch: {
            input: "$name",
            regex: "^M",
            options: "i"
          }
        }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

checkNamePattern();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'startsWithM': {
                    '$regexMatch': {
                        'input': '$name',
                        'regex': '^M',
                        'options': 'i'
                    }
                }
            }
        }
    ]))

    print(result)

    client.close()

check_name_pattern()
```

------

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

5.0 で導入

Amazon DocumentDB の `$replaceAll`演算子は、フィールド内の指定された文字列パターンのすべての出現を新しい文字列に置き換えるために使用されます。この演算子は、データの正規化、テキストクリーニング、文字列操作などのタスクに役立ちます。

**パラメータ**
+ `input`: 置き換える文字列を含むフィールドまたは式。
+ `find`: 検索して置き換える文字列パターン。
+ `replacement`: 一致した出現を置き換える文字列。

## 例 (MongoDB シェル)
<a name="replaceAll-examples"></a>

次の例は、集約パイプラインで `$replaceAll`演算子を使用して、文字列「Chocolatier」のすべての出現を「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) 内の検索の最初の出現を置き換える文字列。

## 例 (MongoDB シェル)
<a name="replaceOne-examples"></a>

次の例は、集約パイプライン内で `$replaceOne`演算子を使用して、製品名の部分文字列を置き換える方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertMany([
  { "_id":1, "productId": "PROD-0Y9GL0", "name": "Gordon's Extra Creamy Milk Chocolate - Pack of 4", "category": "Confectionery", "price": 24.99 },
  { "_id":2, "productId": "PROD-Y2E9H5", "name": "Nutrition Co. - Original Corn Flakes Cereal", "category": "Breakfast Cereals", "price": 8.50 },
  { "_id":3, "productId": "PROD-Z3F8K2", "name": "Gordon's Dark Chocolate (90% Cocoa) Pack - Pack of 4", "category": "Confectionery", "price": 28.99 }
]);
```

**集約の例**

```
db.products.aggregate([
  {
    $addFields: {
      standardizedName: {
        $replaceOne: {
          input: "$name",
          find: "Pack",
          replacement: "Package"
        }
      }
    }
  }
]);
```

**出力**

出力は、各製品名の「Pack」の最初の出現のみが「Package」に置き換えられたことを示しています。

```
[
  {
    _id: 1,
    productId: 'PROD-0Y9GL0',
    name: "Gordon's Extra Creamy Milk Chocolate - Pack of 4",
    category: 'Confectionery',
    price: 24.99,
    standardizedName: "Gordon's Extra Creamy Milk Chocolate - Package of 4"
  },
  {
    _id: 2,
    productId: 'PROD-Y2E9H5',
    name: 'Nutrition Co. - Original Corn Flakes Cereal',
    category: 'Breakfast Cereals',
    price: 8.5,
    standardizedName: 'Nutrition Co. - Original Corn Flakes Cereal'
  },
  {
    _id: 3,
    productId: 'PROD-Z3F8K2',
    name: "Gordon's Dark Chocolate (90% Cocoa) Pack - Pack of 4",
    category: 'Confectionery',
    price: 28.99,
    standardizedName: "Gordon's Dark Chocolate (90% Cocoa) Package - Pack of 4"
  }
```

## コードの例
<a name="replaceOne-code"></a>

`$replaceOne` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const pipeline = [
    {
      $addFields: {
        standardizedName: {
          $replaceOne: {
            input: '$name',
            find: 'Pack',
            replacement: 'Package'
          }
        }
      }
    }
  ];

  const result = await collection.aggregate(pipeline).toArray();
  console.log(result);

  await client.close();
}

replaceOne();
```

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

```
from pymongo import MongoClient

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

    pipeline = [
        {
            '$addFields': {
                'standardizedName': {
                    '$replaceOne': {
                        'input': '$name',
                        'find': 'Pack',
                        'replacement': 'Package'
                    }
                }
            }
        }
    ]

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

    client.close()

replaceOne()
```

------

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

`$replaceRoot` 演算子は、ルートドキュメントを指定された埋め込みドキュメントに置き換えるために使用されます。これは、ネストされたドキュメントを最上位に昇格させたり、データ出力を再構築したりする場合に便利です。

**パラメータ**
+ `newRoot`: 既存のルートドキュメントを置き換える新しいルートドキュメント。

## 例 (MongoDB シェル)
<a name="replaceRoot-examples"></a>

この例では、顧客の注文から配送先住所情報を抽出する方法を示します。これは、配送ラベルまたは住所リストを生成するのに役立ちます。

**サンプルドキュメントを作成する**

```
db.orders.insertMany([
  {
    "_id":1, "orderId": "ORD-2024-001", "customerId": "CUST-12345", "orderDate": "2024-01-15", "shippingAddress": { "name": "María García", "street": "123 Main St", "city": "Seattle", "state": "WA", "zipCode": "98101", "country": "USA" },"totalAmount": 149.99 },
  { "_id":2, "orderId": "ORD-2024-002", "customerId": "CUST-67890", "orderDate": "2024-01-16", "shippingAddress": { "name": "Arnav Desai", "street": "456 Oak Ave", "city": "Portland", "state": "OR", "zipCode": "97201", "country": "USA" }, "totalAmount": 89.50 } ])
```

**クエリの例**

```
db.orders.aggregate([
  {
    $replaceRoot: {
      newRoot: "$shippingAddress"
    }
  }
])
```

**出力**

```
{
    name: 'María García',
    street: '123 Main St',
    city: 'Seattle',
    state: 'WA',
    zipCode: '98101',
    country: 'USA'
  },
  {
    name: 'Arnav Desai',
    street: '456 Oak Ave',
    city: 'Portland',
    state: 'OR',
    zipCode: '97201',
    country: 'USA'
  }
```

## コードの例
<a name="replaceRoot-code"></a>

`$replaceRoot` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

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

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

  const result = await collection.aggregate([
    {
      $replaceRoot: {
        newRoot: "$shippingAddress"
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

extractShippingAddresses();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            "$replaceRoot": {
                "newRoot": "$shippingAddress"
            }
        }
    ]))

    print(result)

    client.close()

extract_shipping_addresses()
```

------

# \$1replaceWith
<a name="replaceWith"></a>

バージョン 8.0 の新機能

Elastic クラスターではサポートされていません。

Amazon DocumentDB の`$replaceWith`集約ステージは、入力ドキュメントを新しいドキュメントに置き換えるために使用されます。\$1id フィールドを含む入力ドキュメントのすべての既存のフィールドは、新しいドキュメントに置き換えられます。 `$replaceWith`は、ドキュメントをフラット化したり、埋め込みドキュメントを最上位レベルに昇格させたりするためによく使用されます。

**パラメータ**
+ `<replacement>` (必須): 既存のドキュメントを置き換える新しいドキュメント。

## 例 (MongoDB シェル)
<a name="replaceWith-examples"></a>

次の例は、 `$replaceWith`演算子を使用して Amazon DocumentDB コレクション内の既存のドキュメントを置き換える方法を示しています。

**サンプルドキュメントを作成する**

```
db.restaurants.insertMany([
  {
    "restaurantId": "REST-0Y9GL0",
    "name": "Biryani Adda",
    "cuisine": "Indian",
    "ratings": [ 3, 4, 3, 2, 2, 4, 1, 5, 5, 5 ]
  },
  {
    "restaurantId": "REST-8L2PX9",
    "name": "The Burger Spot",
    "cuisine": "American",
    "ratings": [ 2, 3, 4, 5, 3, 1, 1, 2, 4 ]
  }
]);
```

**クエリの例**

```
db.restaurants.aggregate([
  { $replaceWith: {
      name: "$name",
      cuisine: "$cuisine",
      rating: { $avg: "$ratings" }
    }
  }
]);
```

**出力**

```
[
  {
    name: 'Biryani Adda',
    cuisine: 'Indian',
    rating: 3.4
  },
  {
    name: 'The Burger Spot',
    cuisine: 'American',
    rating: 2.7777777777777777
  }
]
```

## コードの例
<a name="replaceWith-code"></a>

`$replaceWith` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function replaceDoc() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('restaurants');

  const result = await collection.aggregate([
    { $replaceWith: {
        name: "description_index",
        cuisine: 2,
        rating: { $avg: "$ratings" }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

replaceDoc();
```

------
#### [ Python ]

```
from pymongo import MongoClient


def replace_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.restaurants

    result = list(collection.aggregate([
        {
            '$replaceWith': {
                'name': "$name",
                'cuisine': "$cuisine",
                'rating': { '$avg': "$ratings"}
            }
        }
    ]))

    print(result)
    client.close()

replace_document()
```

------

# \$1reverseArray
<a name="reverseArray"></a>

Amazon DocumentDB の `$reverseArray`演算子は、配列の要素を指定された順序で反転させるために使用されます。この演算子は、配列の要素を逆方向に並べ替える必要がある場合に便利です。

**パラメータ**
+ `expression`: 反転する配列式。

## 例 (MongoDB シェル)
<a name="reverseArray-examples"></a>

次の例は、 `$reverseArray`演算子を使用して配列内の要素の順序を反転する方法を示しています。

**サンプルドキュメントを作成する**

```
db.miles.insertMany([
  { "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ]},
  { "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 2560, 890, 2780]},
  { "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 880]}
]);
```

**クエリの例**

```
db.miles.aggregate([
  {
    $project: {
      _id: 1,
      member_since: 1,
      credit_card: 1,
      reversed_flight_miles: { $reverseArray: "$flight_miles" }
    }
  }
]);
```

**出力**

```
{ "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "reversed_flight_miles" : [ 880, 2560, 1205 ] }
{ "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "reversed_flight_miles" : [ 2780, 890, 2560, 1205 ] }
{ "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "reversed_flight_miles" : [ 880, 1205 ] }
```

この例では、 `$reverseArray`演算子を使用して`flight_miles`配列の順序を逆にします。出力の結果`reversed_flight_miles`フィールドには、配列の要素が逆順に表示されます。

## コードの例
<a name="reverseArray-code"></a>

`$reverseArray` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

Node.js アプリケーションで `$reverseArray`演算子を使用する例を次に示します。

```
const { MongoClient } = require('mongodb');

async function reverseArray() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        member_since: 1,
        credit_card: 1,
        reversed_flight_miles: { $reverseArray: '$flight_miles' }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

reverseArray();
```

------
#### [ Python ]

Python アプリケーションで `$reverseArray`演算子を使用する例を次に示します。

```
from pymongo import MongoClient

def reverse_array():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.miles

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'member_since': 1,
                'credit_card': 1,
                'reversed_flight_miles': { '$reverseArray': '$flight_miles' }
            }
        }
    ]))

    print(result)
    client.close()

reverse_array()
```

------

# \$1rtrim
<a name="rtrim"></a>

バージョン 4.0 の新機能。

Elastic クラスターではサポートされていません。

Amazon DocumentDB の `$rtrim`演算子は、文字列から末尾の文字を削除するために使用されます。デフォルトでは、末尾の空白文字は削除されますが、chars 引数を渡すことで削除する文字のセットを指定することもできます。

**パラメータ**
+ `input`: 末尾の空白文字を削除する入力文字列。
+ `chars`: (オプション) 特定の文字を削除します。

## 例 (MongoDB シェル)
<a name="rtrim-examples"></a>

次の例は、 `$rtrim`演算子を使用して文字列から末尾の指定された文字 (「 \$1」) を削除する方法を示しています。

**サンプルドキュメントを作成する**

```
db.collection.insert([
  { "name": "John Doe*  ", "age": 30 },
  { "name": "Jane Smith  ", "age": 25 },
  { "name": "Bob Johnson", "age": 35 }
]);
```

**クエリの例**

```
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      name: { $rtrim: { input: "$name", chars: " *" } }, 
      age: 1
    }
  }
]);
```

**出力**

```
[
  { age: 30, name: 'John Doe' },
  { age: 25, name: 'Jane Smith' },
  { age: 35, name: 'Bob Johnson' }
]
```

## コードの例
<a name="rtrim-code"></a>

`$rtrim` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient, Bson } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {

    const db = client.db('test');
    const collection = db.collection('collection');  

    const pipeline = [
      {
        $project: {
          _id: 0,
          name: { $rtrim: { input: "$name", chars: " *" } },
          age: 1
        }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();
    console.dir(results, { depth: null });

  } catch (err) {
    console.error('Error occurred:', err);
  } finally {
    await client.close();
  }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    try:

        db = client.test
        collection = db.collection

        pipeline = [
            {
                "$project": {
                    "_id": 0,
                    "name": { "$rtrim": { "input": "$name", "chars": " *" } },
                    "age": 1
                }
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        client.close()

example()
```

------

# \$1sample
<a name="sample"></a>

Amazon DocumentDB の`$sample`集約ステージは、コレクションから指定された数のドキュメントをランダムに選択するために使用されます。これは、データ分析、テスト、さらに処理するためのサンプルの生成などのタスクに役立ちます。

**パラメータ**
+ `size`: ランダムに選択するドキュメントの数。

## 例 (MongoDB シェル)
<a name="sample-examples"></a>

次の例は、 `$sample`ステージを使用して`temp`コレクションから 2 つのドキュメントをランダムに選択する方法を示しています。

**サンプルドキュメントを作成する**

```
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 シェル)
<a name="search-examples"></a>

次の例は、 `$search`演算子を使用してテキスト検索クエリを実行する方法を示しています。

**サンプルドキュメントを作成する**

```
db.textcollection.createIndex({"description": "text"});

db.textcollection.insertMany([
  { _id: 1, name: "John Doe", description: "This is a sample document about John Doe." },
  { _id: 2, name: "Jane Smith", description: "This is a sample document about Jane Smith." },
  { _id: 3, name: "Bob Johnson", description: "This is a sample document about Bob Johnson." },
  { _id: 4, name: "Jon Jeffries", description: "This is a sample document about Jon Jeffries." }
]);
```

**クエリの例**

```
db.textcollection.find(
  { $text: { $search: "John" } }
);
```

**出力**

```
[
  {
    _id: 1,
    name: 'John Doe',
    description: 'This is a sample document about John Doe.'
  }
]
```

## コードの例
<a name="search-code"></a>

`$search` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findWithText() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('textcollection');

  const result = await collection.find(
    { $text: { $search: "John" } }
  ).sort({ score: { $meta: "textScore" } }).toArray();

  console.log(result);
  client.close();
}

findWithText();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_with_text():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['textcollection']

    result = list(collection.find(
        { '$text': { '$search': 'John' } }
    ))

    print(result)
    client.close()

find_with_text()
```

------

# \$1second
<a name="second"></a>

Amazon DocumentDB の `$second`演算子は、日付またはタイムスタンプから秒コンポーネントを抽出します。これは、日付またはタイムスタンプフィールドから秒値を取得するために使用されます。

**パラメータ**
+ `expression`: 秒値を抽出する日付またはタイムスタンプフィールド。この式は、フィールドパスでも、日付またはタイムスタンプに解決される有効な式でもかまいません。

## 例 (MongoDB シェル)
<a name="second-examples"></a>

次の例は、 `$second`演算子を使用して日付フィールドから秒コンポーネントを抽出する方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { name: "John", dob: new Date("1990-05-15T12:30:45Z") },
  { name: "Jane", dob: new Date("1985-09-20T23:59:59Z") },
  { name: "Bob", dob: new Date("2000-01-01T00:00:00Z") }
]);
```

**クエリの例**

```
db.users.aggregate([{ $project: { name: 1, dobSeconds: { $second: "$dob" } } }])
```

**出力**

```
[
  { "_id" : ObjectId("6089a9c306a829d1f8b456a1"), "name" : "John", "dobSeconds" : 45 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a2"), "name" : "Jane", "dobSeconds" : 59 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a3"), "name" : "Bob", "dobSeconds" : 0 }
]
```

## コードの例
<a name="second-code"></a>

`$second` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([{ $project: { name: 1, dobSeconds: { $second: '$dob' } } }]).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = list(users.aggregate([{'$project': {'name': 1, 'dobSeconds': {'$second': '$dob'}}}]))
    print(result)

    client.close()

example ()
```

------

# \$1set
<a name="set-stage"></a>

バージョン 8.0 の新機能

Elastic クラスターではサポートされていません。

Amazon DocumentDB の`$set`集約ステージでは、集約パイプライン中にドキュメントに新しいフィールドを追加したり、既存のフィールド値を更新したりできます。

**パラメータ**
+ `expression`: 評価する式。これは、フィールド参照や算術演算など、任意の有効な集計式にすることができます。

## 例 (MongoDB シェル)
<a name="set-stage-examples"></a>

次の例は、`$set`集計ステージを使用して、 `quantity`フィールドに `price`フィールドを乗算して合計を計算する方法を示しています。

**サンプルドキュメントを作成する**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**集約の例**

```
db.inventory.aggregate([
  {
    $set: {
      total: { $multiply: ["$quantity", "$price"] }
    }
  }
])
```

**出力**

```
[
  {
    _id: ObjectId('69248951d66dcae121d2950d'),
    item: 'pencil',
    quantity: 100,
    price: 0.24,
    total: 24
  },
  {
    _id: ObjectId('69248951d66dcae121d2950e'),
    item: 'pen',
    quantity: 204,
    price: 1.78,
    total: 363.12
  }
]
```

## コードの例
<a name="set-stage-code"></a>

`$set` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const inventory = db.collection('inventory');

  const result = await inventory.aggregate([
      {
        $set: {
          total: { $multiply: ["$quantity", "$price"] }
        }
      }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    inventory = db['inventory']

    result = list(inventory.aggregate([
      {
        "$set": {
          "total": { "$multiply": ["$quantity", "$price"] }
        }
      }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1setDifference
<a name="setDifference"></a>

バージョン 4.0 の新機能。

Amazon DocumentDB の `$setDifference`演算子は、2 つのセットを比較し、最初のセットにはあるが、2 番目のセットにはない要素を返すために使用されます。この演算子は、2 つのセット間で一意の要素を見つけるのに役立ちます。

**パラメータ**
+ `firstSet` : 比較する最初のセット。
+ `secondSet` : 比較する 2 番目のセット。

## 例 (MongoDB シェル)
<a name="setDifference-examples"></a>

次の例は、 `$setDifference`演算子を使用して 2 つのセット間の一意の要素を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
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`演算子は、2 つのセットが等しいかどうかを判断するために使用されます。2 つの配列を比較し、順序に関係なく同じ異なる要素が含まれている`true`場合は を返します。

**パラメータ**
+ `expression1`: 比較する最初の配列。
+ `expression2`: 比較する 2 番目の配列。

## 例 (MongoDB シェル)
<a name="setEquals-examples"></a>

次の例は、 `$setEquals`演算子を使用して 2 つの値のセットを比較する方法を示しています。

**サンプルドキュメントを作成する**

```
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`演算子は、2 つ以上の配列間の共通要素を返すために使用されます。この演算子は、データセットを操作するときに特に役立ち、複数のセットの交差を見つけることができます。

**パラメータ**
+ `array1`: 交差する最初の配列。
+ `array2`: 交差する 2 番目の配列。
+ `arrayN`: (オプション) 交差する追加の配列。

## 例 (MongoDB シェル)
<a name="setIntersection-examples"></a>

次の例は、 `$setIntersection`演算子を使用して 2 つの配列間の共通要素を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.collection.insertMany([
  { _id: 1, colors: ["red", "blue", "green"] },
  { _id: 2, colors: ["blue", "yellow", "orange"] },
  { _id: 3, colors: ["red", "green", "purple"] }
])
```

**クエリの例**

```
db.collection.aggregate([
  { $project: {
      _id: 1,
      commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
    }
  }
])
```

**出力**

```
[
  { "_id": 1, "commonColors": ["red", "blue", "green"] },
  { "_id": 2, "commonColors": ["blue"] },
  { "_id": 3, "commonColors": ["red", "green"] }
]
```

## コードの例
<a name="setIntersection-code"></a>

`$setIntersection` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('mycollection');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['mycollection']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'commonColors': { '$setIntersection': ["$colors", ["red", "blue", "green"]] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1setIsSubset
<a name="setIsSubset"></a>

Amazon DocumentDB の `$setIsSubset`演算子は、値のセットが別のセットのサブセットかどうかを判断するために使用されます。配列フィールドでセットベースの比較とオペレーションを実行するのに役立ちます。

**パラメータ**
+ `field`: `$setIsSubset`演算子を適用するフィールド。
+ `set`: フィールドを比較する セット。

## 例 (MongoDB シェル)
<a name="setIsSubset-examples"></a>

次の例は、 フィールドが指定されたセットの`tags`サブセットであるかどうかをチェックするための `$setIsSubset`演算子の使用を示しています。

**サンプルドキュメントを作成する**

```
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`集計演算子は、2 つ以上の値のセットを組み合わせて、入力セットのすべての一意の要素を含むセットを返すために使用されます。この演算子は、ドキュメントの配列フィールドに対してセットベースのオペレーションを実行する必要がある場合に便利です。

**パラメータ**
+ `expression1`: 配列に解決される式。
+ `expression2`: 配列に解決される式。
+ `expressionN`: 配列に解決される追加の式 (オプション）。

## 例 (MongoDB シェル)
<a name="setUnion-examples"></a>

次の例は、 `$setUnion`演算子を使用して、コレクション内の 2 つの配列フィールドの一意の要素を組み合わせる方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { _id: 1, name: "Alice", hobbies: ["reading", "swimming"], skills: ["coding", "writing"] },
  { _id: 2, name: "Bob", hobbies: ["cooking", "gardening"], skills: ["coding", "photography"] },
  { _id: 3, name: "Charlie", hobbies: ["reading", "painting"], skills: ["gardening", "music"] }
]);
```

**クエリの例**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      allInterests: { $setUnion: ["$hobbies", "$skills"] }
    }
  }
]);
```

**出力**

```
[
  { "_id" : 1, "name" : "Alice", "allInterests" : [ "coding", "reading", "swimming", "writing" ] },
  { "_id" : 2, "name" : "Bob", "allInterests" : [ "coding", "cooking", "gardening", "photography" ] },
  { "_id" : 3, "name" : "Charlie", "allInterests" : [ "gardening", "music", "painting", "reading" ] }
]
```

この例では、 `$setUnion`演算子を使用して、各ユーザードキュメントの `hobbies`および `skills`配列フィールドの一意の要素を組み合わせます。結果の`allInterests`フィールドには、各ユーザーのすべての固有の趣味とスキルの結合が含まれます。

## コードの例
<a name="setUnion-code"></a>

`$setUnion` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([
    {
      $project: {
        _id: 1,
        name: 1,
        allInterests: { $setUnion: ["$hobbies", "$skills"] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = list(users.aggregate([
        {
            '$project': {
                '_id': 1,
                'name': 1,
                'allInterests': { '$setUnion': ["$hobbies", "$skills"] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1skip
<a name="skip"></a>

Amazon DocumentDB では、 `$skip`演算子を使用してクエリ結果の開始ポイントをオフセットし、一致するドキュメントの特定のサブセットを取得できます。これは、後続の結果ページを取得するページ分割シナリオで特に便利です。

**パラメータ**
+ `skip`: 残りのドキュメントを返す前にスキップするドキュメントの数。

## 例 (MongoDB シェル)
<a name="skip-examples"></a>

次の例は、 `$skip`演算子を使用してコレクションから結果の 2 ページ目 (ドキュメント 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 項目や下位 N 項目など、配列フィールドから限られた数の項目を表示するために使用されます。

**パラメータ**
+ `array`: スライスする配列フィールド。
+ `n`: 返す要素の数を指定する整数。正の値は配列の先頭から始まり、負の値は配列の末尾から始まります。

## 例 (MongoDB シェル)
<a name="slice-examples"></a>

次の例は、 `$slice`を使用して各シェフの最初の 2 つのお気に入りのお菓子を返す方法を示しています。

**サンプルドキュメントを作成する**

```
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`配列から最初の 2 つの要素を抽出します。

## コードの例
<a name="slice-code"></a>

`$slice` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('sweets');

  const result = await collection.aggregate([
    { $project: { name: 1, topTwoFavorites: { $slice: ['$favorites', 2] } } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['sweets']

    result = list(collection.aggregate([
        { '$project': { 'name': 1, 'topTwoFavorites': { '$slice': ['$favorites', 2] } } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1size
<a name="size"></a>

`$size` 演算子は、配列フィールド内の項目の数を返すために使用されます。これは、ドキュメントに保存されている配列内の要素の数を決定するために使用できます。

**パラメータ**
+ `field`: 配列サイズを返すフィールドパス。

## 例 (MongoDB シェル)
<a name="size-examples"></a>

この例では、 `$size`演算子を使用して、各ユーザーがフォローしているチームの数を返す方法を示します。

**サンプルドキュメントを作成する**

```
db.profiles.insertMany([
  { _id: 1, name: "John Doe", teams: ["Acme", "Widgets", "Gadgets"] },
  { _id: 2, name: "Jane Smith", teams: ["Acme", "Gadgets"] },
  { _id: 3, name: "Bob Johnson", teams: ["Acme", "Widgets", "Gadgets"] }
]);
```

**クエリの例**

```
db.profiles.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      "numberOfTeams": { $size: "$teams" }
    }
  }
])
```

**出力**

```
[
  { name: 'John Doe', numberOfTeams: 3 },
  { name: 'Jane Smith', numberOfTeams: 2 },
  { name: 'Bob Johnson', numberOfTeams: 3 }
]
```

## コードの例
<a name="size-code"></a>

`$size` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const profiles = db.collection('profiles');

  const result = await profiles.aggregate([
    {
      $project: {
        item: 1,
        "numberOfTeams": { $size: "$teams" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    profiles = db.profiles

    result = list(profiles.aggregate([
        {
            '$project': {
                'item': 1,
                'numberOfTeams': { '$size': '$teams' }
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1sort
<a name="sort"></a>

`$sort` 集約ステージは、指定されたフィールド値に基づいてパイプライン内のドキュメントを順序付けします。ドキュメントは、指定されたソート基準に従って昇順または降順に並べられます。

**パラメータ**
+ `field`: ソートするフィールド名。
+ `order`: 昇順`-1`または降順`1`に使用します。

## 例 (MongoDB シェル)
<a name="sort-examples"></a>

次の例は、 `$sort`ステージを使用して製品を価格順に降順で注文する方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", category: "Electronics", price: 1200 },
  { _id: 2, name: "Mouse", category: "Electronics", price: 25 },
  { _id: 3, name: "Desk", category: "Furniture", price: 350 },
  { _id: 4, name: "Chair", category: "Furniture", price: 150 },
  { _id: 5, name: "Monitor", category: "Electronics", price: 400 }
]);
```

**クエリの例**

```
db.products.aggregate([
  { $sort: { price: -1 } }
]);
```

**出力**

```
[
  { _id: 1, name: 'Laptop', category: 'Electronics', price: 1200 },
  { _id: 5, name: 'Monitor', category: 'Electronics', price: 400 },
  { _id: 3, name: 'Desk', category: 'Furniture', price: 350 },
  { _id: 4, name: 'Chair', category: 'Furniture', price: 150 },
  { _id: 2, name: 'Mouse', category: 'Electronics', price: 25 }
]
```

## コードの例
<a name="sort-code"></a>

`$sort` 集約ステージを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.aggregate([
    { $sort: { price: -1 } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.aggregate([
        { '$sort': { 'price': -1 } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1split
<a name="split"></a>

Amazon DocumentDB の`$split`集計演算子は、指定された区切り文字に基づいて文字列を部分文字列の配列に分割するために使用されます。これは、複雑な文字列フィールドを解析し、個々のコンポーネントを抽出してさらに処理する場合に便利です。

**パラメータ**
+ `string`: 分割する文字列。
+ `delimiter`: 入力文字列を分割するために使用される文字または文字列。

## 例 (MongoDB シェル)
<a name="split-examples"></a>

この例では、 `$split`を使用して「Desk」フィールドのコンポーネントを配列に分割し、データの処理を容易にします。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
```

**クエリの例**

```
db.people.aggregate([
  { $project: { parts: { $split: ["$Desk", "-"] } } }
]);
```

**出力**

```
{ "_id" : 1, "parts" : [ "Düsseldorf", "BVV", "021" ] }
{ "_id" : 2, "parts" : [ "Munich", "HGG", "32a" ] }
{ "_id" : 3, "parts" : [ "Cologne", "ayu", "892.50" ] }
{ "_id" : 4, "parts" : [ "Dortmund", "Hop", "78" ] }
```

の出力は、従業員の情報を表示するためにアプリケーションで使用できる配列`$split`を作成します。

## コードの例
<a name="split-code"></a>

`$split` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const result = await db.collection('people').aggregate([
    { $project: { parts: { $split: ['$Desk', '-'] } } }
  ]).toArray();
  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    result = list(db.people.aggregate([
        { '$project': { 'parts': { '$split': ['$Desk', '-'] } } }
    ]))
    print(result)
    client.close()

example()
```

------

# \$1sqrt
<a name="sqrt"></a>

バージョン 4.0 の新機能。

Amazon DocumentDB の `$sqrt`演算子は、数値の平方根を計算するために使用されます。

**パラメータ**
+ `expression`: 引数は、負以外の数値に解決される限り、任意の有効な式にすることができます。

## 例 (MongoDB シェル)
<a name="sqrt-examples"></a>

次の例は、`$sqrt`演算子を使用して数値の平方根を計算する方法を示しています。

**サンプルドキュメントを作成する**

```
db.numbers.insertMany([
  { "_id": 1, "number": 16 },
  { "_id": 2, "number": 36 },
  { "_id": 3, "number": 64 }
]);
```

**クエリの例**

```
db.numbers.aggregate([
  { $project: {
    "_id": 1,
    "square_root": { $sqrt: "$number" }
  }}
]);
```

**出力**

```
[
  { _id: 1, square_root: 4 },
  { _id: 2, square_root: 6 },
  { _id: 3, square_root: 8 }
]
```

## コードの例
<a name="sqrt-code"></a>

`$sqrt` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
      await client.connect();

      const db = client.db('test');
      const collection = db.collection('numbers');

      const pipeline = [
        {
          $project: {
            _id: 1,
            square_root: { $sqrt: '$number' }
          }
        }
      ];

      const results = await collection.aggregate(pipeline).toArray();

      console.dir(results, { depth: null });

    } finally {
      await client.close();
    }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
  
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

  try:
      db = client.test
      collection = db.numbers

      pipeline = [
          {
              "$project": {
                  "_id": 1,
                  "square_root": { 
                    "$sqrt": "$number" 
                  }
              }
          }
      ]

      results = collection.aggregate(pipeline)

      for doc in results:
          print(doc)

  except Exception as e:
      print(f"An error occurred: {e}")

  finally:
      client.close()

example()
```

------

# \$1strLenBytes
<a name="strLenBytes"></a>

Amazon DocumentDB の `$strLenBytes`演算子は、文字列の長さをバイト単位で決定するために使用されます。これは、文字列フィールドのストレージサイズを理解する必要がある場合、特に 1 文字あたり 1 バイト以上を使用する Unicode 文字を処理する場合に便利です。

**パラメータ**
+ `expression`: 長さを計算する文字列式。

## 例 (MongoDB シェル)
<a name="strLenBytes-examples"></a>

この例では、 `$strLenBytes`演算子を使用して文字列フィールドの長さをバイト単位で計算する方法を示します。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
```

**クエリの例**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenBytes: "$Desk" }
    }
  }
])
```

**出力**

```
{ "_id" : 1, "Desk" : "Düsseldorf-BVV-021", "length" : 19 }
{ "_id" : 2, "Desk" : "Munich-HGG-32a", "length" : 14 }
{ "_id" : 3, "Desk" : "Cologne-ayu-892.50", "length" : 18 }
{ "_id" : 4, "Desk" : "Dortmund-Hop-78", "length" : 15 }
```

「Düsseldorf-BVV-021」文字列の長さは 19 バイトです。Unicode 文字「Ü」が 2 バイトを占めるため、コードポイント (18) の数とは異なります。

## コードの例
<a name="strLenBytes-code"></a>

`$strLenBytes` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    {
      $project: {
        "Desk": 1,
        "length": { $strLenBytes: "$Desk" }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                "Desk": 1,
                "length": { "$strLenBytes": "$Desk" }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1strLenCP
<a name="strLenCP"></a>

Amazon DocumentDB の `$strLenCP`演算子は、コードポイントの文字列式の長さ (Unicode 文字) を決定するために使用されます。これは、バイト数ではなく文字列内の文字数を知る必要がある場合に便利です。

**パラメータ**
+ `expression`: コードポイントで長さを返す文字列式。

## 例 (MongoDB シェル)
<a name="strLenCP-examples"></a>

次の例は、 `$strLenCP`演算子を使用して Unicode 文字を含む文字列の長さを決定する方法を示しています。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
])
```

**クエリの例**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenCP: "$Desk" }
    }
  }
])
```

**出力**

```
{ "_id" : 1, "Desk" : "Düsseldorf-BVV-021", "length" : 18 }
{ "_id" : 2, "Desk" : "Munich-HGG-32a", "length" : 14 }
{ "_id" : 3, "Desk" : "Cologne-ayu-892.50", "length" : 18 }
{ "_id" : 4, "Desk" : "Dortmund-Hop-78", "length" : 15 }
```

Unicode 文字 (Ü) を含む「Düsseldorf-BVV-021」文字列の長さ測定の違いに注目してください。`$strLenCP` 演算子は Unicode 文字数を正しくカウントし、`$strLenBytes`演算子はバイト数をカウントします。

## コードの例
<a name="strLenCP-code"></a>

`$strLenCP` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

以下は、MongoDB ドライバーで Node.js アプリケーションで `$strLenCP`演算子を使用する例です。

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    {
      $project: {
        "Desk": 1,
        "length": { $strLenCP: "$Desk" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

PyMongo ドライバーで Python アプリケーションで `$strLenCP`演算子を使用する例を次に示します。

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                "Desk": 1,
                "length": { "$strLenCP": "$Desk" }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1strcasecmp
<a name="strcasecmp"></a>

Amazon DocumentDB の `$strcasecmp`演算子は、2 つの文字列間で大文字と小文字を区別しない比較を実行します。2 つの入力文字列の辞書比較を示す整数値が返され、大文字と小文字の違いは無視されます。

**パラメータ**
+ `string1`: 比較する最初の文字列。
+ `string2`: 比較する 2 番目の文字列。

## 例 (MongoDB シェル)
<a name="strcasecmp-examples"></a>

この例では、 `$strcasecmp`演算子を使用して`people`コレクション内のデスクの場所文字列を比較し、大文字と小文字の違いを無視する方法を示します。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "_id": 1, "Desk": "mke233-wi" },
  { "_id": 2, "Desk": "MKE233-WI" },
  { "_id": 3, "Desk": "mke233-wi" }
]);
```

**クエリの例**

```
db.people.aggregate([
  {
    $project: {
      item: 1,
      compare: { $strcasecmp: ["$Desk", "mke233-wi"] }
    }
  }
]);
```

**出力**

```
{ "_id" : 1, "compare" : 0 }
{ "_id" : 2, "compare" : 0 }
{ "_id" : 3, "compare" : 0 }
```

出力は、 `&quot;Desk&quot;`フィールドと文字列の比較が 3 つのドキュメントすべて`0`に対して を`&quot;mke233-wi&quot;`返し、大文字と小文字が無視された場合に文字列が等しいことを示します。

## コードの例
<a name="strcasecmp-code"></a>

`$strcasecmp` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        compare: { $strcasecmp: ["$Desk", "mke233-wi"] }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'compare': { '$strcasecmp': ['$Desk', 'mke233-wi'] }
            }
        }
    ]))

    print(result)

    client.close()

example()
```

------

# \$1substr
<a name="substr"></a>

Amazon DocumentDB の `$substr`演算子は、特定の文字列から部分文字列を抽出するために使用されます。これは、バイトの範囲ではなく文字の範囲に基づいて部分文字列を定義する必要がある場合に特に便利です。これは、文字を表すために使用されるバイト数が異なる可能性がある Unicode 文字列を処理する場合に特に重要です。

**パラメータ**
+ `string`: 部分文字列を抽出する入力文字列。
+ `start`: 抽出する部分文字列の開始位置 (ゼロベース）。負以外の整数式にすることができます。
+ `length`: 抽出された部分文字列の文字数。負以外の整数式にすることができます。

## 例 (MongoDB シェル)
<a name="substr-examples"></a>

この例では、 を使用して従業員のデスクの場所から状態の略語を`$substr`抽出する方法を示します。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-NRW-021" },
  { "_id": 2, "Desk": "Bremerhaven-HBB-32a" },
  { "_id": 3, "Desk": "Norderstedt-SHH-892.50" },
  { "_id": 4, "Desk": "Brandenburg-BBB-78" }
]);
```

**クエリの例**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substr: ["$Desk", 12, 3] }
    }
  }
])
```

**出力**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

## コードの例
<a name="substr-code"></a>

`$substr` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function example() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const collection = db.collection("people");

  const result = await collection.aggregate([
    {
      $project: {
        "state": { $substrCP: ["$Desk", 12, 3] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    collection = db["people"]

    result = list(collection.aggregate([
        {
            "$project": {
                "state": { "$substrCP": ["$Desk", 12, 3] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1substrBytes
<a name="substrBytes"></a>

Amazon DocumentDB の `$substrBytes`演算子は、指定されたバイト範囲に基づいて文字列から部分文字列を抽出するために使用されます。この演算子は、文字列から部分文字列を抽出する必要があり、文字列内の各文字を表すために必要なバイト数が重要である場合に便利です。

Unicode コードポイントの数で動作する とは異なり`$substrCP`、 は文字列内の文字を表すために必要なバイト数で`$substrBytes`動作します。これは、ASCII 以外の文字を含む文字列を使用する場合に特に便利です。これらの文字では、表すために複数のバイトが必要になる可能性があるためです。

\$1注:\$1 `$substr`はバージョン 3.4 以降廃止されました。 `$substr`は のエイリアスになりました`$substrBytes`。

**パラメータ**
+ `string`: 部分文字列が抽出される入力文字列。
+ `startByte`: 抽出する部分文字列のゼロベースの開始バイト位置。負の値を使用して、文字列の末尾から位置を指定できます。
+ `length`: 抽出する部分文字列のバイト数。

## 例 (MongoDB シェル)
<a name="substrBytes-examples"></a>

この例では、 `$substrBytes` を使用して、ASCII 以外の文字を含む文字列から部分文字列を抽出します。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-NRW-021" },
  { "_id": 2, "Desk": "Bremerhaven-HBB-32a" },
  { "_id": 3, "Desk": "Norderstedt-SHH-892.50" },
  { "_id": 4, "Desk": "Brandenburg-BBB-78" }
]);
```

**クエリの例**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrBytes: [ "$Desk", 12, 3] }
    }
  }
])
```

**出力**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

この例では、 `$substrBytes`を使用して、 `Desk`フィールドの 12 バイト目から 3 バイトの部分文字列を抽出します。これにより、文字列に ASCII 以外の文字が含まれている場合でも、2 文字の状態の略語を抽出できます。

## コードの例
<a name="substrBytes-code"></a>

`$substrBytes` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const people = db.collection('people');

  const result = await people.aggregate([
    {
      $project: {
        "state": { $substrBytes: ["$Desk", 12, 3] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    people = db.people

    result = list(people.aggregate([
        {
            '$project': {
                "state": { '$substrBytes': ["$Desk", 12, 3] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1substrCP
<a name="substrCP"></a>

Amazon DocumentDB の `$substrCP`演算子は、文字列から部分文字列を抽出するために使用されます。部分文字列は UTF-8 コードポイント (CP) の範囲として指定されます。この演算子は、文字の基になるバイト表現を心配することなく部分文字列を抽出できるため、Unicode 文字列を使用する場合に特に便利です。

バイト位置で動作する `$substrBytes` 演算子とは異なり、 `$substrCP`演算子はコードポイント位置を操作します。これにより、コードポイントの数がバイト数や文字数と一致しない可能性があるため、ASCII 以外の文字を含む文字列の操作が容易になります。

**パラメータ**
+ `string`: 部分文字列を抽出する入力文字列。
+ `start`: 部分文字列を抽出する開始コードポイントの位置 (ゼロベース）。
+ `length`: 抽出するコードポイントの数。

## 例 (MongoDB シェル)
<a name="substrCP-examples"></a>

この例では、 `$substrCP`演算子を使用して、従業員のデスクの場所を含む文字列から状態の略語を抽出します。

**サンプルドキュメントを作成する**

```
db.people.insert([
  { "_id": 1, "first_name": "Jane", "last_name": "Doe", "Desk": "12 Main St, Minneapolis, MN 55401" },
  { "_id": 2, "first_name": "John", "last_name": "Doe", "Desk": "456 Oak Rd, New Orleans, LA 70032" },
  { "_id": 3, "first_name": "Steve", "last_name": "Smith", "Desk": "789 Elm Ln, Bakersfield, CA 93263" }
]);
```

**クエリの例**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrCP: ["$Desk", 25, 2] }
    }
  }
]);
```

**出力**

```
{ "_id" : 1, "state" : "MN" }
{ "_id" : 2, "state" : "LA" }
{ "_id" : 3, "state" : "CA" }
```

この例では、状態の略語は `Desk`フィールドの 25 番目のコードポイントで始まり、2 つのコードポイントの長さであることがわかっています。`$substrCP` 演算子を使用すると、文字列の基になるバイト表現について心配することなく、状態の略語を抽出できます。

## コードの例
<a name="substrCP-code"></a>

`$substrCP` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findStates() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const result = await db.collection('people').aggregate([
    {
      $project: {
        "state": { $substrCP: ["$Desk", 25, 2] }
      }
    }
  ]).toArray();
  console.log(result);
  client.close();
}

findStates();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_states():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    result = list(db.people.aggregate([
        {
            '$project': {
                'state': { '$substrCP': ['$Desk', 25, 2] }
            }
        }
    ]))
    print(result)
    client.close()

find_states()
```

Node.js と Python の両方の例では、MongoDB シェルの例と同様に、 `$substrCP`演算子を使用して `Desk`フィールドから状態の略語を抽出します。

------

# \$1subtract
<a name="subtract"></a>

Amazon DocumentDB の `$subtract`演算子は、値を減算するために使用されます。日付、数値、またはその両方の組み合わせを減算するために使用できます。この演算子は、2 つの日付の差を計算する場合や、数値から値を引く場合に便利です。

**パラメータ**
+ `expression1`: 減算される最初の値。
+ `expression2`: から減算される 2 番目の値`<expression1>`。

## 例 (MongoDB シェル)
<a name="subtract-examples"></a>

次の例は、 `$subtract`演算子を使用して 2 つの日付の差を計算する方法を示しています。

**サンプルドキュメントを作成する**

```
db.dates.insert([
  {
  "_id": 1,
  "startDate": ISODate("2023-01-01T00:00:00Z"),
  "endDate": ISODate("2023-01-05T12:00:00Z")
  }
]);
```

**クエリの例**

```
db.dates.aggregate([
  {
    $project: {
      _id: 1,
      durationDays: {
        $divide: [
          { $subtract: ["$endDate", "$startDate"] },
          1000 * 60 * 60 * 24  // milliseconds in a day
        ]
      }
    }
  }
]);
```

**出力**

```
[ { _id: 1, durationDays: 4.5 } ]
```

この例では、 `$subtract`演算子を使用して `$endDate`と の差を日`$startDate`単位で計算します。

## コードの例
<a name="subtract-code"></a>

`$subtract` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();
    const db = client.db('test');
    const collection = db.collection('dates');

    const pipeline = [
      {
        $project: {
          _id: 1,
          durationDays: {
            $divide: [
              { $subtract: ["$endDate", "$startDate"] },
              1000 * 60 * 60 * 24  // Convert milliseconds to days
            ]
          }
        }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();

    console.dir(results, { depth: null });

  } finally {
    await client.close();
  }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from datetime import datetime, timedelta
from pymongo import MongoClient

def example():
  
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    try:
        db = client.test
        collection = db.dates

        pipeline = [
            {
                "$project": {
                    "_id": 1,
                    "durationDays": {
                        "$divide": [
                            { "$subtract": ["$endDate", "$startDate"] },
                            1000 * 60 * 60 * 24  # Convert milliseconds to days
                        ]
                    }
                }
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        client.close()

example()
```

------

# \$1sum
<a name="sum"></a>

Amazon DocumentDB の `$sum`演算子は、グループ内のドキュメントごとに指定された式の合計を返します。これは、集計パイプラインの \$1group ステージで集計計算を実行するために通常使用されるグループアキュムレータ演算子です。

**パラメータ**
+ `expression`: 合計する数値式。これは、フィールドパス、式、または定数です。

## 例 (MongoDB シェル)
<a name="sum-examples"></a>

次の例は、 `$sum`演算子を使用して各製品の総売上を計算する方法を示しています。

**サンプルドキュメントを作成する**

```
db.sales.insertMany([
  { product: "abc", price: 10, quantity: 2 },
  { product: "abc", price: 10, quantity: 3 },
  { product: "xyz", price: 20, quantity: 1 },
  { product: "xyz", price: 20, quantity: 5 }
]);
```

**クエリの例**

```
db.sales.aggregate([
  { $group: {
      _id: "$product",
      totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } }
    }}
]);
```

**出力**

```
[
  { "_id": "abc", "totalSales": 50 },
  { "_id": "xyz", "totalSales": 120 }
]
```

## コードの例
<a name="sum-code"></a>

`$sum` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('sales');

    const result = await collection.aggregate([
      { $group: {
          _id: "$product",
          totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } }
        }}
    ]).toArray();

    console.log(result);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from pprint import pprint

def example():
    client = None
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

        db = client.test
        collection = db.sales

        result = list(collection.aggregate([
            { '$group': {
                '_id': '$product',
                'totalSales': { '$sum': { '$multiply': [ '$price', '$quantity' ] } }
            }}
        ]))

        pprint(result)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        if client:
            client.close()

example()
```

------

# \$1switch
<a name="switch"></a>

バージョン 4.0 の新機能。

Elastic クラスターではサポートされていません。

`$switch` 演算子は Amazon DocumentDB の条件式演算子で、ケース式のリストを評価し、 が true に評価される最初のケースの値、またはケース式が true でない場合はデフォルト値を返すことができます。

**パラメータ**
+ `branches`: ドキュメントの配列。各ドキュメントには、評価するブール式を含む大文字と小文字のフィールドと、大文字と小文字の式が true の場合に返す値を含むフィールドがあります。
+ `default`: (オプション) いずれの大文字と小文字の式も true でない場合に返す値。

## 例 (MongoDB シェル)
<a name="switch-examples"></a>

次の例は、 `$switch`演算子を使用して、注文の合計に基づいて注文の配送コストを決定する方法を示しています。

**サンプルドキュメントを作成する**

```
db.orders.insertMany([
  { _id: 1, total: 50 },
  { _id: 2, total: 150 },
  { _id: 3, total: 250 }
]);
```

**クエリの例**

```
db.orders.aggregate([
  {
    $project: {
      _id: 1,
      total: 1,
      shippingCost: {
        $switch: {
          branches: [
            { case: { $lte: ["$total", 100] }, then: 5 },
            { case: { $lte: ["$total", 200] }, then: 10 },
            { case: { $gt: ["$total", 200] }, then: 15 }
          ],
          default: 0
        }
      }
    }
  }
])
```

**出力**

```
[
  {
    "_id": 1,
    "total": 50,
    "shippingCost": 5
  },
  {
    "_id": 2,
    "total": 150,
    "shippingCost": 10
  },
  {
    "_id": 3,
    "total": 250,
    "shippingCost": 15
  }
]
```

## コードの例
<a name="switch-code"></a>

`$switch` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        total: 1,
        shippingCost: {
          $switch: {
            branches: [
              { case: { $lte: ['$total', 100] }, then: 5 },
              { case: { $lte: ['$total', 200] }, then: 10 },
              { case: { $gt: ['$total', 200] }, then: 15 }
            ],
            default: 0
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.orders

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'total': 1,
                'shippingCost': {
                    '$switch': {
                        'branches': [
                            { 'case': { '$lte': ['$total', 100] }, 'then': 5 },
                            { 'case': { '$lte': ['$total', 200] }, 'then': 10 },
                            { 'case': { '$gt': ['$total', 200] }, 'then': 15 }
                        ],
                        'default': 0
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1toBool
<a name="toBool"></a>

Amazon DocumentDB の `$toBool`演算子は、式をブール値に変換します。

**パラメータ**
+ `expression`: ブール値に変換される式。

**注**: 文字列は に変換されます`true`。

## 例 (MongoDB シェル)
<a name="toBool-examples"></a>

次の例は、 `$toBool`演算子を使用して、さまざまなデータ型からデバイス状態値を正規化する方法を示しています。

**サンプルドキュメントを作成する**

```
db.deviceStates.insertMany([
  { _id: 1, deviceId: "sensor-001", status: true },
  { _id: 2, deviceId: "camera-002", status: 1 },
  { _id: 3, deviceId: "thermostat-003", status: "active" },
  { _id: 4, deviceId: "doorlock-004", status: 0 }
]);
```

**クエリの例**

```
db.deviceStates.aggregate([
  {
    $project: {
      _id: 1,
      deviceId: 1,
      isActive: { $toBool: "$status" }
    }
  }
]);
```

**出力**

```
[
  { "_id": 1, "deviceId": "sensor-001", "isActive": true },
  { "_id": 2, "deviceId": "camera-002", "isActive": true },
  { "_id": 3, "deviceId": "thermostat-003", "isActive": true },
  { "_id": 4, "deviceId": "doorlock-004", "isActive": false }
]
```

## コードの例
<a name="toBool-code"></a>

`$toBool` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('deviceStates');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        deviceId: 1,
        isActive: { $toBool: '$status' }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['deviceStates']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'deviceId': 1,
                'isActive': { '$toBool': '$status' }
            }
        }
    ]))

    print(result)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1toDate
<a name="toDate"></a>

バージョン 4.0 の新機能

Amazon DocumentDB の`$toDate`集計演算子は、日付または日付と時刻の文字列を BSON 日付タイプに変換するために使用されます。これは、 `$dateToString`演算子の逆オペレーションです。

**パラメータ**
+ `dateString`: BSON 日付タイプに変換される日付または日時の文字列表現。
+ `format`: (オプション) の形式を指定する文字列`dateString`。指定しない場合、演算子はさまざまな標準的な日付と時刻`dateString`の形式で を解析しようとします。
+ `timezone`: (オプション) 変換に使用するタイムゾーンを表す文字列。指定しない場合、ローカルタイムゾーンが使用されます。

## 例 (MongoDB シェル)
<a name="toDate-examples"></a>

次の例は、 `$toDate`演算子を使用して日付文字列を BSON 日付タイプに変換する方法を示しています。

**サンプルドキュメントを作成する**

```
db.events.insertMany([
  { _id: 1, eventName: "Mission Start", eventTime: "2023-04-15T10:30:00Z" },
  { _id: 2, eventName: "Checkpoint Reached", eventTime: "2023-04-15T11:15:00Z" },
  { _id: 3, eventName: "Mission End", eventTime: "2023-04-15T12:00:00Z" }
]);
```

**クエリの例**

```
db.events.aggregate([
  {
    $project: {
      eventName: 1,
      eventTimeDate: { $toDate: "$eventTime" }
    }
  }
]);
```

**出力**

```
[
  {
    "_id": 1,
    "eventName": "Mission Start",
    "eventTimeDate": ISODate("2023-04-15T10:30:00Z")
  },
  {
    "_id": 2,
    "eventName": "Checkpoint Reached",
    "eventTimeDate": ISODate("2023-04-15T11:15:00Z")
  },
  {
    "_id": 3,
    "eventName": "Mission End",
    "eventTimeDate": ISODate("2023-04-15T12:00:00Z")
  }
]
```

## コードの例
<a name="toDate-code"></a>

`$toDate` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  const result = await collection.aggregate([
    {
      $project: {
        eventName: 1,
        eventTimeDate: { $toDate: '$eventTime' }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    result = list(collection.aggregate([
        {
            '$project': {
                'eventName': 1,
                'eventTimeDate': { '$toDate': '$eventTime' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toDecimal
<a name="toDecimal"></a>

バージョン 4.0 の新機能

Amazon DocumentDB の `$toDecimal`演算子は、値を Decimal128 データ型に変換するために使用されます。これは、正確な 10 進演算を実行したり、ダブルデータ型を使用して正確に表現できない大きな 10 進値を処理したりする必要がある場合に便利です。

**パラメータ**
+ `expression`: Decimal128 データ型に変換する式。

## 例 (MongoDB シェル)
<a name="toDecimal-examples"></a>

この例では、 `$toDecimal`演算子を使用して文字列値を Decimal128 データ型に変換する方法を示します。

**サンプルドキュメントを作成する**

```
db.numbers.insertOne({ _id: 1, value: "3.14" });
db.numbers.insertOne({ _id: 2, value: "2.71" });
```

**クエリの例**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    decimalValue: { $toDecimal: "$value" }
  }}
])
```

**出力**

```
[
  { "_id" : 1, "decimalValue" : Decimal128("3.14") },
  { "_id" : 2, "decimalValue" : Decimal128("2.71") }
]
```

## コードの例
<a name="toDecimal-code"></a>

`$toDecimal` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      _id: 1,
      decimalValue: { $toDecimal: "$value" }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.numbers

    result = list(collection.aggregate([
        {'$project': {
            '_id': 1,
            'decimalValue': {'$toDecimal': '$value'}
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toDouble
<a name="toDouble"></a>

バージョン 4.0 の新機能

Amazon DocumentDB の `$toDouble`演算子は、値を倍精度の 64 ビット浮動小数点数に変換するために使用されます。これは、元々数値形式でない値に対して算術演算を実行する必要がある場合に便利です。

**パラメータ**

`&lt;expression&gt;`: 二重値に変換する式。これは、数値、文字列、またはブール値に解決される任意の有効な式にすることができます。

## 例 (MongoDB シェル)
<a name="toDouble-examples"></a>

この例では、 `$toDouble`演算子を使用して、数学的計算を実行するために文字列値を数値に変換する方法を示します。

**サンプルドキュメントを作成する**

```
db.numbers.insertMany([
  { _id: 1, value: "10.5" },
  { _id: 2, value: "20.25" },
  { _id: 3, value: "7" }
])
```

**クエリの例**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      value: 1,
      double_value: { $toDouble: "$value" },
      double_plus_five: { $add: [{ $toDouble: "$value" }, 5] }
    }
  }
])
```

**出力**

```
[
  { "_id" : 1, "value" : "10.5", "double_value" : 10.5, "double_plus_five" : 15.5 },
  { "_id" : 2, "value" : "20.25", "double_value" : 20.25, "double_plus_five" : 25.25 },
  { "_id" : 3, "value" : "7", "double_value" : 7.0, "double_plus_five" : 12.0 }
]
```

## コードの例
<a name="toDouble-code"></a>

`$toDouble` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        value: 1,
        double_value: { $toDouble: "$value" },
        double_plus_five: { $add: [{ $toDouble: "$value" }, 5] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'value': 1,
                'double_value': { '$toDouble': '$value' },
                'double_plus_five': { '$add': [{ '$toDouble': '$value' }, 5] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toInt
<a name="toInt"></a>

バージョン 4.0 の新機能

Amazon DocumentDB の `$toInt`演算子は、入力値を整数データ型に変換するために使用されます。この演算子は、フィールドまたは式が整数として表されるようにする必要がある場合に便利です。これは、特定のオペレーションやデータ処理タスクにとって重要です。

**パラメータ**
+ `expression`: 整数に変換される式。

## 例 (MongoDB シェル)
<a name="toInt-examples"></a>

次の例は、 `$toInt`演算子を使用して文字列値を整数に変換する方法を示しています。

**サンプルドキュメントを作成する**

```
db.numbers.insertMany([
  { "name": "one", "value": "1" },
  { "name": "hundred", "value": "100" }
]);
```

**クエリの例**

```
db.numbers.aggregate([
  { $project: {
    "_id": 0,
    "name": 1,
    "intValue": { $toInt: "$value" }
  }}
]);
```

**出力**

```
{ "name": "one", "intValue": 1 }
{ "name": "hundred", "intValue": 100 }
```

## コードの例
<a name="toInt-code"></a>

`$toInt` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      "_id": 0,
      "name": 1,
      "intValue": { $toInt: "$value" }
    }}
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        { "$project": {
            "_id": 0,
            "name": 1,
            "intValue": { "$toInt": "$value" }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toLong
<a name="toLong"></a>

バージョン 4.0 の新機能

Amazon DocumentDB の `$toLong`演算子は、値を 64 ビット整数 (ロング) データ型に変換するために使用されます。これは、文字列やその他のデータ型として保存される可能性のある数値に対して算術演算または比較を実行する必要がある場合に便利です。

**パラメータ**
+ `expression`: 64 ビット整数に変換する式。

## 例 (MongoDB シェル)
<a name="toLong-examples"></a>

この例では、 `$toLong`演算子を使用して文字列値を 64 ビット整数に変換する方法を示します。

**サンプルドキュメントを作成する**

```
db.numbers.insertMany([
  { _id: 1, value: "42" },
  { _id: 3, value: "9223372036854775807" }
]);
```

**クエリの例**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      longValue: { $toLong: "$value" }
    }
  }
])
```

**出力**

```
[
  { "_id" : 1, "longValue" : 42 },
  { "_id" : 3, "longValue" : 9223372036854775807 }
]
```

## コードの例
<a name="toLong-code"></a>

`$toLong` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const numbers = db.collection('numbers');

  const result = await numbers.aggregate([
    {
      $project: {
        _id: 1,
        longValue: { $toLong: "$value" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    numbers = db.numbers

    result = list(numbers.aggregate([
        {
            '$project': {
                '_id': 1,
                'longValue': { '$toLong': '$value' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toLower
<a name="toLower"></a>

Amazon DocumentDB の `$toLower`演算子は、文字列を小文字に変換するために使用されます。

**パラメータ**
+ `expression`: 小文字に変換する文字列式。

## 例 (MongoDB シェル)
<a name="toLower-examples"></a>

次の例は、 `$toLower`演算子を使用して `Desk`フィールドを小文字に変換する方法を示しています。

**サンプルドキュメントを作成する**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" }
]);
```

**クエリの例**

```
db.locations.aggregate([
  { $project: { item: { $toLower: "$Desk" } } }
]);
```

**出力**

```
{ "_id" : 1, "item" : "düsseldorf-bvv-021" }
{ "_id" : 2, "item" : "munich-hgg-32a" }
```

## コードの例
<a name="toLower-code"></a>

`$toLower` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function main() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const collection = db.collection("locations");

  const result = await collection.aggregate([
    { $project: { item: { $toLower: "$Desk" } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    collection = db["locations"]

    result = list(collection.aggregate([
        { "$project": { "item": { "$toLower": "$Desk" } } }
    ]))

    print(result)

    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1toObjectId
<a name="toObjectId"></a>

バージョン 4.0 の新機能

Amazon DocumentDB の `$toObjectId`演算子は、ObjectId の文字列表現を実際の ObjectId データ型に変換するために使用されます。これは、ObjectIds、ObjectId の文字列表現として保存されたデータを操作する場合に便利です。

**パラメータ**
+ `expression`: 有効な ObjectId を表す文字列式。

## 例 (MongoDB シェル)
<a name="toObjectId-examples"></a>

次の例は、 `$toObjectId`演算子を使用して ObjectId の文字列表現を ObjectId データ型に変換する方法を示しています。

**サンプルドキュメントを作成する**

```
db.employees.insertMany([
  { _id: 1, empId:"64e5f8886218c620cf0e8f8a", name: "Carol Smith", employeeId: "c720a" },
  { _id: 2, empId:"64e5f94e6218c620cf0e8f8c", name: "Bill Taylor", employeeId: "c721a" }
]);
```

**クエリの例**

```
db.employees.aggregate([
  { $project: {
    "empIdAsObjectId": {$toObjectId: "$empId"}}
  }
]);
```

**出力**

```
[
  { _id: 1, empIdAsObjectId: ObjectId('64e5f8886218c620cf0e8f8a') },
  { _id: 2, empIdAsObjectId: ObjectId('64e5f94e6218c620cf0e8f8c') }
]
```

## コードの例
<a name="toObjectId-code"></a>

`$toObjectId` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('employees');

  const result = await collection.aggregate([
    { $project: {
      "empIdAsObjectId": {$toObjectId: "$empId"}}
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['employees']

    result = list(collection.aggregate([
      { "$project": {
        "empIdAsObjectId": {"$toObjectId": "$empId"}}
      }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toString
<a name="toString"></a>

バージョン 4.0 の新機能

Amazon DocumentDB の `$toString`演算子は、任意のタイプ (null を除く) の値を文字列表現に変換するために使用されます。これは、元々文字列形式でない値に対して文字列オペレーションを実行する必要がある場合に便利です。

**パラメータ**
+ `expression`: 文字列に変換する式。

## 例 (MongoDB シェル)
<a name="toString-examples"></a>

次の例は、 `$toString`演算子を使用して数値を文字列に変換する方法を示しています。

**サンプルドキュメントを作成する**

```
db.numbers.insertMany([
  { "_id": 1, "value": 42 },
  { "_id": 2, "value": 3.14 }
]);
```

**クエリの例**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    valueAsString: { $toString: "$value" }
  }}
]);
```

**出力**

```
{ "_id": 1, "valueAsString": "42" }
{ "_id": 2, "valueAsString": "3.14" }
```

## コードの例
<a name="toString-code"></a>

`$toString` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      _id: 1,
      valueAsString: { $toString: '$value' }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        { '$project': {
            '_id': 1,
            'valueAsString': { '$toString': '$value' }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toUpper
<a name="toUpper"></a>

Amazon DocumentDB の `$toUpper`演算子は、文字列を大文字に変換するために使用されます。

**パラメータ**
+ `expression`: 大文字に変換する文字列式。

## 例 (MongoDB シェル)
<a name="toUpper-examples"></a>

次の例は、 `$toUpper`演算子を使用して `Desk`フィールドを大文字に変換する方法を示しています。

**サンプルドキュメントを作成する**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "düsseldorf-bvv-021" },
  { "_id": 2, "Desk": "munich-hgg-32a" }
]);
```

**クエリの例**

```
db.locations.aggregate([
  { $project: { item: { $toUpper: "$Desk" } } }
]);
```

**出力**

```
{ "_id" : 1, "item" : "DüSSELDORF-BVV-021" }
{ "_id" : 2, "item" : "MUNICH-HGG-32A" }
```

## コードの例
<a name="toUpper-code"></a>

`$toUpper` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('locations');

  const result = await collection.aggregate([
    { $project: { item: { $toUpper: '$Desk' } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['locations']

    result = list(collection.aggregate([
        { '$project': { 'item': { '$toUpper': '$Desk' } } }
    ]))

    print(result)

    client.close()

example()
```

------

# \$1trim
<a name="trim"></a>

バージョン 4.0 の新機能

Amazon DocumentDB の `$trim`演算子は、文字列から先頭および/または末尾の空白文字を削除するために使用されます。

**パラメータ**
+ `input`: トリミングする文字列式。
+ `chars`: (オプション) 入力の最初と最後にトリミングする文字を指定します。デフォルトは空白です。

## 例 (MongoDB シェル)
<a name="trim-examples"></a>

次の例は、 `$trim`演算子を使用して文字列から先頭と末尾の空白を削除する方法を示しています。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { "name": "   John Doe   " },
  { "name": "   Bob Johnson   " }
])
```

**クエリの例**

```
db.people.aggregate([
  { $project: {
    "name": { $trim: {input: "$name"}}
  }}
])
```

**出力**

```
[
  { "name": "John Doe" },
  { "name": "Bob Johnson" }
]
```

## コードの例
<a name="trim-code"></a>

`$trim` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    { $project: {
      "name": { $trim: {input: "$name" }}
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']

    result = list(collection.aggregate([
        {"$project": {
            "name": {"$trim": {"input": "$name"}}
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1type
<a name="type-aggregation"></a>

`$type` 集計演算子は、指定されたフィールドの BSON データ型を返します。これは、集計オペレーション中にフィールド値のデータ型を識別するのに役立ちます。

**パラメータ**
+ `expression`: 返される型を持つフィールドまたは式。

## 例 (MongoDB シェル)
<a name="type-aggregation-examples"></a>

次の例は、 `$type`演算子を使用して、各製品の料金フィールドのデータ型を識別する方法を示しています。

**サンプルドキュメントを作成する**

```
db.inventory.insertMany([
  { _id: 1, item: "Notebook", price: 15.99 },
  { _id: 2, item: "Pen", price: "2.50" },
  { _id: 3, item: "Eraser", price: 1 },
  { _id: 4, item: "Ruler", price: null }
]);
```

**クエリの例**

```
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      price: 1,
      priceType: { $type: "$price" }
    }
  }
]);
```

**出力**

```
[
  { _id: 1, item: 'Notebook', price: 15.99, priceType: 'double' },
  { _id: 2, item: 'Pen', price: '2.50', priceType: 'string' },
  { _id: 3, item: 'Eraser', price: 1, priceType: 'int' },
  { _id: 4, item: 'Ruler', price: null, priceType: 'null' }
]
```

## コードの例
<a name="type-aggregation-code"></a>

`$type` 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        price: 1,
        priceType: { $type: "$price" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'price': 1,
                'priceType': { '$type': '$price' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1unset
<a name="unset-stage"></a>

バージョン 8.0 の新機能

Elastic クラスターではサポートされていません。

Amazon DocumentDB の`$unset`集約ステージでは、ドキュメントからフィールドを削除できます。

**パラメータ**
+ `expression`: フィールド名または複数のフィールド名のリスト。

## 例 (MongoDB シェル)
<a name="unset-stage-examples"></a>

次の例は、`$unset`集約ステージを使用して `price`フィールドを削除する方法を示しています。

**サンプルドキュメントを作成する**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**集約の例**

```
db.inventory.aggregate([
  {
    $unset: "price"
  }
])
```

**出力**

```
[
  {
    _id: ObjectId('69248951d66dcae121d2950d'),
    item: 'pencil',
    quantity: 100
  },
  {
    _id: ObjectId('69248951d66dcae121d2950e'),
    item: 'pen',
    quantity: 204
  }
]
```

## コードの例
<a name="unset-stage-code"></a>

`$unset` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const inventory = db.collection('inventory');

  const result = await inventory.aggregate([
      {
        $unset: "price"
      }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    inventory = db['inventory']

    result = list(inventory.aggregate([
      {
        "$unset": "price"
      }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1unwind
<a name="unwind"></a>

`$unwind` 演算子は、入力ドキュメントから配列フィールドを分解して、各要素のドキュメントを出力するために使用されます。これは、データのフィルタリング、ソート、変換など、配列の個々の要素に対してオペレーションを実行する場合に便利です。

**パラメータ**
+ `path`: 巻き出す配列フィールドへのパス。
+ `includeArrayIndex`: (オプション) 配列要素のインデックスを保持する新しいフィールドの名前を指定します。
+ `preserveNullAndEmptyArrays`: (オプション) 配列フィールドが null または空の配列の場合、オペレーションが元のドキュメントを保持するかどうかを決定します。

## 例 (MongoDB シェル)
<a name="unwind-examples"></a>

次の例は、 `$unwind`演算子を使用して配列フィールドを分解し、個々の要素に対して追加のオペレーションを実行する方法を示しています。

**サンプルドキュメントを作成する**

```
db.people.insertMany([
  { _id: 1, name: "jon", hobbies: ["painting", "dancing", "singing"] },
  { _id: 2, name: "jane", hobbies: ["reading", "swimming"] },
  { _id: 3, name: "jack", hobbies: [] }
])
```

**クエリの例**

```
db.people.aggregate([
  { $unwind: "$hobbies" }
])
```

**出力**

```
[
  { _id: 1, name: 'jon', hobbies: 'painting' },
  { _id: 1, name: 'jon', hobbies: 'dancing' },
  { _id: 1, name: 'jon', hobbies: 'singing' },
  { _id: 2, name: 'jane', hobbies: 'reading' },
  { _id: 2, name: 'jane', hobbies: 'swimming' }
]
```

## コードの例
<a name="unwind-code"></a>

`$unwind` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    { $unwind: '$hobbies' }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']

    result = list(collection.aggregate([
        { '$unwind': '$hobbies' }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1vectorSearch
<a name="vectorSearch"></a>

バージョン 8.0 の新機能

Elastic クラスターではサポートされていません。

Amazon DocumentDB の `$vectorSearch`演算子を使用すると、ベクトル検索を実行できます。ベクトル検索は、距離または類似度メトリクスを使用してベクトル表現を比較することで、機械学習で同様のデータポイントを見つけるために使用される方法です。この機能は、JSON ベースのドキュメントデータベースの柔軟性と豊富なクエリとベクトル検索の能力を組み合わせることで、セマンティック検索、製品レコメンデーションなどの機械学習や生成 AI のユースケースを構築できます。

**パラメータ**
+ `<exact>` (オプション): Exact Nearest Neighbor (ENN) または Approximate Nearest Neighbor (ANN) 検索を実行するかどうかを指定するフラグ。値は次のいずれかになります。
+ false - ANN 検索を実行するには
+ true - ENN 検索を実行するには

省略するか false に設定する場合は、 `numCandidates`が必要です。

```
- `<index>` : Name of the Vector Search index to use.
- `<limit>` : Number of documents to return in the results.
- `<numCandidates>` (optional): This field is required if 'exact' is false or omitted. Number of nearest neighbors to use during the search. Value must be less than or equal to (<=) 10000. You can't specify a number less than the number of documents to return ('limit').
- `<path>` : Indexed vector type field to search.
- `<queryVector>` : Array of numbers that represent the query vector.
```

## 例 (MongoDB シェル)
<a name="vectorSearch-examples"></a>

次の例は、 `$vectorSearch`演算子を使用して、ベクトル表現に基づいて同様の製品説明を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertMany([
  {
    _id: 1,
    name: "Product A",
    description: "A high-quality, eco-friendly product for your home.",
    description_vector: [ 0.2, 0.5, 0.8 ]
  },
  {
    _id: 2,
    name: "Product B",
    description: "An innovative and modern kitchen appliance.",
    description_vector: [0.7, 0.3, 0.9]
  },
  {
    _id: 3,
    name: "Product C",
    description: "A comfortable and stylish piece of furniture.",
    description_vector: [0.1, 0.2, 0.4]
  }
]);
```

**ベクトル検索インデックスを作成する**

```
db.runCommand(
    {
        createIndexes: "products",
        indexes: [{
            key: {
                "description_vector": "vector"
            },
            vectorOptions: {
                type: "hnsw",
                dimensions: 3,
                similarity: "cosine",
                m: 16,
                efConstruction: 64
            },
            name: "description_index"
        }]
    }
);
```

**クエリの例**

```
db.products.aggregate([
  { $vectorSearch: {
      index: "description_index",
      limit: 2,
      numCandidates: 10,
      path: "description_vector",
      queryVector: [0.1, 0.2, 0.3]
    }
  }
]);
```

**出力**

```
[
  {
    "_id": 1,
    "name": "Product A",
    "description": "A high-quality, eco-friendly product for your home.",
    "description_vector": [ 0.2, 0.5, 0.8 ]
  },
  {
    "_id": 3,
    "name": "Product C",
    "description": "A comfortable and stylish piece of furniture.",
    "description_vector": [ 0.1, 0.2, 0.4 ]
  }
]
```

## コードの例
<a name="vectorSearch-code"></a>

`$vectorSearch` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findSimilarProducts(queryVector) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.aggregate([
    { $vectorSearch: {
        index: "description_index",
        limit: 2,
        numCandidates: 10,
        path: "description_vector",
        queryVector: queryVector
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

findSimilarProducts([0.1, 0.2, 0.3]);
```

------
#### [ Python ]

```
from pymongo import MongoClient


def find_similar_products(query_vector):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    result = list(collection.aggregate([
        {
            '$vectorSearch': {
                'index': "description_index",
                'limit': 2,
                'numCandidates': 10,
                'path': "description_vector",
                'queryVector': query_vector
            }
        }
    ]))

    print(result)
    client.close()

find_similar_products([0.1, 0.2, 0.3])
```

------

# \$1week
<a name="week"></a>

Amazon DocumentDB の`$week`演算子は、ISO 8601 標準に基づいて日付の週番号 (0～53) を返します。週番号は年と曜日に基づいて計算され、月曜日を週の最初の日として使用します。

**パラメータ**

なし

## 例 (MongoDB シェル)
<a name="week-examples"></a>

次の例は、 `$week`演算子を使用して特定の日付の週番号を取得する方法を示しています。

**サンプルドキュメントを作成する**

```
db.events.insertMany([
  { _id: 1, date: new Date("2023-01-01") },
  { _id: 2, date: new Date("2023-01-08") },
  { _id: 3, date: new Date("2023-12-31") }
]);
```

**クエリの例**

```
db.events.aggregate([
  { $project: {
    _id: 1,
    week: { $week: "$date" }
  }}
]);
```

**出力**

```
[
  { "_id": 1, "week": 1 },
  { "_id": 2, "week": 2 },
  { "_id": 3, "week": 53 }
]
```

## コードの例
<a name="week-code"></a>

`$week` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('events');

  const result = await events.aggregate([
    { $project: {
      _id: 1,
      week: { $week: "$date" }
    }}
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
  db = client['test']
  events = db['events']

  result = list(events.aggregate([
      {'$project': {
          '_id': 1,
          'week': {'$week': '$date'}
      }}
  ]))

  print(result)

  client.close()

example()
```

------

# \$1year
<a name="year"></a>

Amazon DocumentDB の `$year`演算子は、日付またはタイムスタンプから年コンポーネントを抽出します。

**パラメータ**
+ `expression`: 年コンポーネントを抽出する日付またはタイムスタンプ式。

## 例 (MongoDB シェル)
<a name="year-examples"></a>

次の例は、 `$year`演算子を使用して日付フィールドから年コンポーネントを抽出する方法を示しています。

**サンプルドキュメントを作成する**

```
db.events.insertMany([
  { "_id": 1, "date": ISODate("2023-04-15T00:00:00Z") },
  { "_id": 3, "date": ISODate("2021-12-31T00:00:00Z") }
]);
```

**クエリの例**

```
db.events.aggregate([
  { $project: { year: { $year: "$date" } } }
]);
```

**出力**

```
[
  { "_id": 1, "year": 2023 },
  { "_id": 3, "year": 2021 }
]
```

## コードの例
<a name="year-code"></a>

`$year` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  const result = await collection.aggregate([
    { $project: { year: { $year: "$date" } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    result = list(collection.aggregate([
        {'$project': {'year': {'$year': '$date'}}}
    ]))

    print(result)

    client.close()

example()
```

------

# \$1zip
<a name="zip"></a>

Amazon DocumentDB の `$zip`演算子を使用すると、複数の配列を 1 つのタプルの配列 (キーと値のペア) に結合できます。これは、ドキュメント内のさまざまなソースまたは配列のデータを組み合わせて、新しいドキュメントまたはオブジェクトを作成する必要がある場合に便利です。

**パラメータ**
+ `inputs`: 配列に解決される式の配列。これらの配列は 1 つのタプル配列に結合されます。
+ `useLongestLength`: (オプション) の場合`true`、出力配列は最長の入力配列の長さになり、短い配列は`null`値でパディングされます。の場合`false`、出力配列は最短の入力配列の長さになります。
+ `defaults`: (オプション) 対応する入力配列が最長の入力配列より短く、 `useLongestLength` が の場合にタプルに使用するデフォルト値の配列`true`。

## 例 (MongoDB シェル)
<a name="zip-examples"></a>

次の例は、 `$zip`演算子を使用して 2 つの配列を 1 つのタプル配列に結合する方法を示しています。

**サンプルドキュメントを作成する**

```
db.grades.insert([
  {
    "_id": 1,
    "name": "John",
    "scores": [90, 85, 92],
    "classes": ["Math", "English", "Science"]
  },
  {
    "_id": 2,
    "name": "Jane",
    "scores": [88, 91, 90, 85],
    "classes": ["Math", "English", "Science", "History"]
  }
])
```

**クエリの例**

```
db.grades.aggregate([
  {
    $project: {
      "name": 1,
      "scoredClasses": {
        $zip: {
          inputs: ["$scores", "$classes"],
          useLongestLength: true,
          defaults: [null, null]
        }
      }
    }
  }
])
```

**出力**

```
[
  {
    "_id": 1,
    "name": "John",
    "scoredClasses": [
      [90, "Math"],
      [85, "English"],
      [92, "Science"],
      [null, null]
    ]
  },
  {
    "_id": 2,
    "name": "Jane",
    "scoredClasses": [
      [88, "Math"],
      [91, "English"],
      [90, "Science"],
      [85, "History"]
    ]
  }
]
```

## コードの例
<a name="zip-code"></a>

`$zip` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('grades');

  const result = await collection.aggregate([
    {
      $project: {
        "name": 1,
        "scoredClasses": {
          $zip: {
            inputs: ["$scores", "$classes"],
            useLongestLength: true,
            defaults: [null, null]
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['grades']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'scoredClasses': {
                    '$zip': {
                        'inputs': ['$scores', '$classes'],
                        'useLongestLength': True,
                        'defaults': [None, None]
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# 地理空間
<a name="mongo-apis-geospatial-operators"></a>

このセクションでは、Amazon DocumentDB でサポートされている地理空間演算子に関する詳細情報を提供します。

**Topics**
+ [\$1geometry](geometry.md)
+ [\$1geoIntersects](geoIntersects.md)
+ [\$1geoWithin](geoWithin.md)
+ [\$1maxDistance](maxDistance.md)
+ [\$1minDistance](minDistance.md)
+ [\$1near](near.md)
+ [\$1nearSphere](nearSphere.md)

# \$1geometry
<a name="geometry"></a>

Amazon DocumentDB の `$geometry`演算子は、地理空間クエリの一部として GeoJSON ジオメトリオブジェクトを指定するために使用されます。この演算子は、 `$geoWithin`や などの他の地理空間クエリ演算子と組み合わせて`$geoIntersects`使用され、データに対して空間クエリを実行します。

Amazon DocumentDB では、`$geometry`演算子は次の GeoJSON ジオメトリタイプをサポートしています。
+ Point
+ LineString
+ Polygon
+ MultiPoint
+ MultiLineString
+ MultiPolygon
+ GeometryCollection

**パラメータ**
+ `type`: GeoJSON ジオメトリオブジェクトのタイプ。例: 、 `Point` `Polygon`など。
+ `coordinates`: ジオメトリを表す座標の配列。座標配列の構造は、ジオメトリタイプによって異なります。

## 例 (MongoDB シェル)
<a name="geometry-examples"></a>

次の例は、 `$geometry`演算子を使用して Amazon DocumentDB で`$geoIntersects`クエリを実行する方法を示しています。

**サンプルドキュメントを作成する**

```
db.locations.insertMany([
  { 
    "_id": 1,
    "name": "Location 1",
    "location": { 
      "type": "Point",
      "coordinates": [-73.983253, 40.753941]
    }
  },
  { 
    "_id": 2,
    "name": "Location 2", 
    "location": {
      "type": "Polygon",
      "coordinates": [[
        [-73.998427, 40.730309],
        [-73.954348, 40.730309],
        [-73.954348, 40.780816],
        [-73.998427, 40.780816],
        [-73.998427, 40.730309]
      ]]
    }
  }
]);
```

**クエリの例**

```
db.locations.find({
  "location": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Polygon",
        "coordinates": [[
          [-73.998, 40.730],
          [-73.954, 40.730],
          [-73.954, 40.781],
          [-73.998, 40.781],
          [-73.998, 40.730]
        ]]
      }
    }
  }
})
```

**出力**

```
[
  {
    "_id": 2,
    "name": "Location 2",
    "location": {
      "type": "Polygon",
      "coordinates": [
        [
          [-73.998427, 40.730309],
          [-73.954348, 40.730309],
          [-73.954348, 40.780816],
          [-73.998427, 40.780816],
          [-73.998427, 40.730309]
        ]
      ]
    }
  }
]
```

## コードの例
<a name="geometry-code"></a>

`$geometry` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('locations');

  const query = {
    "location": {
      "$geoIntersects": {
        "$geometry": {
          "type": "Polygon",
          "coordinates": [[
            [-73.998, 40.730],
            [-73.954, 40.730],
            [-73.954, 40.781],
            [-73.998, 40.781],
            [-73.998, 40.730]
          ]]
        }
      }
    }
  };

  const result = await collection.find(query).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['locations']

    query = {
        "location": {
            "$geoIntersects": {
                "$geometry": {
                    "type": "Polygon",
                    "coordinates": [[
                        [-73.998, 40.730],
                        [-73.954, 40.730],
                        [-73.954, 40.781],
                        [-73.998, 40.781],
                        [-73.998, 40.730]
                    ]]
                }
            }
        }
    }

    result = list(collection.find(query))
    print(result)

    client.close()

example()
```

------

# \$1geoIntersects
<a name="geoIntersects"></a>

Amazon DocumentDB の `$geoIntersects`演算子は、地理空間データが指定された GeoJSON オブジェクトと交差するドキュメントを検索するために使用されます。この演算子は、ポリゴンやマルチポリゴンなど、特定の地理的形状との空間関係に基づいてドキュメントを識別する必要があるアプリケーションに役立ちます。

**パラメータ**
+ `$geometry`: 交差をチェックするシェイプを表す GeoJSON オブジェクト。サポートされている GeoJSON オブジェクトタイプは、`Point`、`LineString`、`Polygon`、および です`MultiPolygon`。

## 例 (MongoDB シェル)
<a name="geoIntersects-examples"></a>

次の例は、 `$geoIntersects`演算子を使用して Amazon DocumentDB 内の特定の座標セットの状態名を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.states.insertMany([
  {
    "name": "New York",
    "loc": {
      "type": "Polygon",
      "coordinates": [[
        [-74.25909423828125, 40.47556838210948],
        [-73.70819091796875, 40.47556838210948],
        [-73.70819091796875, 41.31342607582222],
        [-74.25909423828125, 41.31342607582222],
        [-74.25909423828125, 40.47556838210948]
      ]]
    }
  },
  {
    "name": "California",
    "loc": {
      "type": "Polygon",
      "coordinates": [[
        [-124.4091796875, 32.56456771381587],
        [-114.5458984375, 32.56456771381587],
        [-114.5458984375, 42.00964153424558],
        [-124.4091796875, 42.00964153424558],
        [-124.4091796875, 32.56456771381587]
      ]]
    }
  }
]);
```

**クエリの例**

```
var location = [-73.965355, 40.782865];

db.states.find({
  "loc": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Point",
        "coordinates": location
      }
    }
  }
}, {
  "name": 1
});
```

**出力**

```
{ "_id" : ObjectId("536b0a143004b15885c91a2c"), "name" : "New York" }
```

## コードの例
<a name="geoIntersects-code"></a>

`$geoIntersects` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findStateByGeoIntersects(longitude, latitude) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('states');

  const query = {
    loc: {
      $geoIntersects: {
        $geometry: {
          type: 'Point',
          coordinates: [longitude, latitude]
        }
      }
    }
  };

  const projection = {
    _id: 0,
    name: 1
  };

  const document = await collection.findOne(query, { projection });

  await client.close();
  
  if (document) {
    return document.name;
  } else {
    throw new Error('The geo location you entered was not found in the United States!');
  }
}
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_state_by_geointersects(longitude, latitude):
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        db = client.test
        collection_states = db.states

        query_geointersects = {
            "loc": {
                "$geoIntersects": {
                    "$geometry": {
                        "type": "Point",
                        "coordinates": [longitude, latitude]
                    }
                }
            }
        }

        document = collection_states.find_one(query_geointersects,
                                              projection={
                                                  "_id": 0,
                                                  "name": 1
                                              })
        if document is not None:
            state_name = document['name']
            return state_name
        else:
            raise Exception("The geo location you entered was not found in the United States!")
    except Exception as e:
        print('Exception in geoIntersects: {}'.format(e))
        raise
    finally:
        if client is not None:
            client.close()
```

------

# \$1geoWithin
<a name="geoWithin"></a>

Amazon DocumentDB の `$geoWithin`演算子は、位置データ (GeoJSON オブジェクトとして表されます) がポリゴンやマルチポリゴンなどの指定されたシェイプ内に完全に含まれているドキュメントを検索するために使用されます。これは、特定の地理的リージョン内にあるオブジェクトのクエリに役立ちます。

**パラメータ**
+ `$geometry`: クエリ対象のシェイプを表す GeoJSON オブジェクト。

## 例 (MongoDB シェル)
<a name="geoWithin-examples"></a>

次の例は、 `$geoWithin`演算子を使用して、ニューヨーク州内にあるすべての空港を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
// Insert state document
db.states.insert({
    "name": "New York",
    "loc": {
        "type": "Polygon",
        "coordinates": [[
            [-79.76278, 45.0],
            [-73.94, 45.0],
            [-73.94, 40.5],
            [-79.76278, 40.5],
            [-79.76278, 45.0]
        ]]
    }
});

// Insert airport documents
db.airports.insert([
    {
        "name": "John F. Kennedy International Airport",
        "type": "airport",
        "code": "JFK",
        "loc": {
            "type": "Point",
            "coordinates": [-73.7781, 40.6413]
        }
    },
    {
        "name": "LaGuardia Airport",
        "type": "airport",
        "code": "LGA",
        "loc": {
            "type": "Point",
            "coordinates": [-73.8772, 40.7769]
        }
    },
    {
        "name": "Buffalo Niagara International Airport",
        "type": "airport",
        "code": "BUF",
        "loc": {
            "type": "Point",
            "coordinates": [-78.7322, 42.9403]
        }
    }
]);
```

**クエリの例**

```
var state = db.states.findOne({"name": "New York"});

db.airports.find({
    "loc": {
        "$geoWithin": {
            "$geometry": state.loc
        }
    }
}, {
    "name": 1,
    "type": 1,
    "code": 1,
    "_id": 0
});
```

**出力**

```
[
  {
    "name": "John F. Kennedy International Airport",
    "type": "airport",
    "code": "JFK"
  },
  {
    "name": "LaGuardia Airport",
    "type": "airport",
    "code": "LGA"
  }
]
```

## コードの例
<a name="geoWithin-code"></a>

`$geoWithin` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findAirportsWithinState(stateName) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');

  const stateDoc = await db.collection('states').findOne({ name: stateName }, { projection: { _id: 0, loc: 1 } });
  const airportDocs = await db.collection('airports').find({
    loc: {
      $geoWithin: {
        $geometry: stateDoc.loc
      }
    }
  }, { projection: { name: 1, type: 1, code: 1, _id: 0 } }).toArray();

  console.log(airportDocs);

  await client.close();
}

findAirportsWithinState('New York');
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_airports_within_state(state_name):
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        db = client['test']
        state_doc = db.states.find_one({'name': state_name}, {'_id': 0, 'loc': 1})
        airport_docs = db.airports.find({
            'loc': {
                '$geoWithin': {
                    '$geometry': state_doc['loc']
                }
            }
        }, {'name': 1, 'type': 1, 'code': 1, '_id': 0})
        
        return list(airport_docs)
    except Exception as e:
        print(f'Error: {e}')
    finally:
        client.close()

airports = find_airports_within_state('New York')
print(airports)
```

------

# \$1maxDistance
<a name="maxDistance"></a>

Amazon DocumentDB の `$maxDistance`演算子は、クエリ結果に含めるためにドキュメントを含める必要がある GeoJSON ポイントからの最大距離 (メートル単位) を指定するために使用されます。この演算子は、地理空間クエリを実行するために `$nearSphere`演算子と組み合わせて使用されます。

**パラメータ**
+ `$maxDistance`: クエリ結果に含めるためにドキュメントが置かなければならない参照ポイントからの最大距離 (メートル単位）。

## 例 (MongoDB シェル)
<a name="maxDistance-examples"></a>

次の例は、Amazon DocumentDB で `$maxDistance`演算子を使用して、ボストンから 100 km 以内のすべての州都を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
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` は、中心点から少なくとも指定された最小距離にあるドキュメントをフィルタリング`$geoNear`するために、 `$nearSphere`または と組み合わせて使用される検索演算子です。この演算子は Amazon DocumentDB でサポートされており、MongoDB の対応する関数と同様に機能します。

**パラメータ**
+ `$minDistance`: 結果にドキュメントを含めるための中心点からの最小距離 (メートル単位）。

## 例 (MongoDB シェル)
<a name="minDistance-examples"></a>

この例では、ワシントン州シアトルの特定の場所から半径 2 km 以内のすべてのレストランを見つけます。

**サンプルドキュメントを作成する**

```
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`演算子は、指定されたポイントに地理的に近いドキュメントを検索するために使用されます。距離順に並べられたドキュメントが返され、最も近いドキュメントが最初に返されます。この演算子には 2 次元地理空間インデックスが必要で、位置データの近接クエリに役立ちます。

**パラメータ**
+ `$geometry`: ニアクエリの中心点を定義する GeoJSON ポイントオブジェクト。
+ `$maxDistance`: (オプション) ドキュメントがクエリに一致するように指定ポイントからメートル単位の最大距離。
+ `$minDistance`: (オプション) ドキュメントがクエリに一致するように指定ポイントからメートル単位の最小距離。

**インデックスの要件**
+ `2dsphere index`: GeoJSON ポイントデータの地理空間クエリに必要です。

## 例 (MongoDB シェル)
<a name="near-examples"></a>

次の例は、 `$near`演算子を使用して、ワシントン州シアトルの特定の場所に最も近いレストランを見つける方法を示しています。

**サンプルドキュメントを作成する**

```
db.usarestaurants.insert([
  {
    "name": "Noodle House",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.8,
    "location": { "type": "Point", "coordinates": [-122.3517, 47.6159] }
  },
  {
    "name": "Pike Place Grill",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.2,
    "location": { "type": "Point", "coordinates": [-122.3403, 47.6062] }
  },
  {
    "name": "Lola",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.5,
    "location": { "type": "Point", "coordinates": [-122.3407, 47.6107] }
  }
]);
```

**2dsphere インデックスを作成する**

```
db.usarestaurants.createIndex({ "location": "2dsphere" });
```

**GeoJSON ポイントを使用したクエリの例**

```
db.usarestaurants.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $maxDistance: 100,
      $minDistance: 10
    }
  }
});
```

**出力**

```
{
  "_id" : ObjectId("69031ec9ea1c2922a1ce5f4a"),
  "name" : "Noodle House",
  "city" : "Seattle",
  "state" : "Washington",
  "rating" : 4.8,
  "location" : {
    "type" : "Point",
    "coordinates" : [ -122.3517, 47.6159 ]
  }
}
```

## コードの例
<a name="near-code"></a>

`$near` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findNearbyRestaurants() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const restaurants = db.collection('usarestaurants');

  // Create 2dsphere index
  await restaurants.createIndex({ "location": "2dsphere" });

  const result = await restaurants.find({
    location: {
      $near: {
        $geometry: {
          type: "Point",
          coordinates: [-122.3516, 47.6156]
        },
        $maxDistance: 100,
        $minDistance: 10
      }
    }
  }).toArray();

  console.log(result);

  client.close();
}

findNearbyRestaurants();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_nearby_restaurants():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    restaurants = db['usarestaurants']

    # Create 2dsphere index
    restaurants.create_index([("location", "2dsphere")])

    result = list(restaurants.find({
        'location': {
            '$near': {
                '$geometry': {
                    'type': 'Point',
                    'coordinates': [-122.3516, 47.6156]
                },
                '$maxDistance': 100,
                '$minDistance': 10
            }
        }
    }))

    print(result)

    client.close()

find_nearby_restaurants()
```

------

# \$1nearSphere
<a name="nearSphere"></a>

Amazon DocumentDB の `$nearSphere`演算子は、地理空間ポイントから指定された距離内にあるドキュメントを検索するために使用されます。この演算子は、特定の場所の特定の半径内のすべてのレストランを検索するなど、地理空間クエリに特に役立ちます。

**パラメータ**
+ `$geometry`: 参照ポイントを表す GeoJSON オブジェクト。`type` フィールドと `coordinates`フィールドを持つ`Point`オブジェクトである必要があります。
+ `$minDistance`: (オプション) ドキュメントが置かなければならない参照ポイントからの最小距離 (メートル単位）。
+ `$maxDistance`: (オプション) ドキュメントが置かなければならない参照ポイントからの最大距離 (メートル単位）。

## 例 (MongoDB シェル)
<a name="nearSphere-examples"></a>

この例では、ワシントン州シアトルの特定の場所から 2 キロメートル (2000 メートル) 以内にすべてのレストランがあります。

**サンプルドキュメントを作成する**

```
db.usarestaurants.insert([
  {
    name: "Noodle House",
    location: { type: "Point", coordinates: [-122.3516, 47.6156] }
  },
  {
    name: "Pike Place Grill",
    location: { type: "Point", coordinates: [-122.3403, 47.6101] }
  },
  {
    name: "Seattle Coffee Co.",
    location: { type: "Point", coordinates: [-122.3339, 47.6062] }
  }
]);
```

**クエリの例**

```
db.usarestaurants.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $minDistance: 1,
      $maxDistance: 2000
    }
  }
}, {
  name: 1
});
```

**出力**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## コードの例
<a name="nearSphere-code"></a>

`$nearSphere` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findNearbyRestaurants() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const restaurants = db.collection('usarestaurants');

  const result = await restaurants.find({
    location: {
      $nearSphere: {
        $geometry: {
          type: "Point",
          coordinates: [-122.3516, 47.6156]
        },
        $minDistance: 1,
        $maxDistance: 2000
      }
    }
  }, {
    projection: { name: 1 }
  }).toArray();

  console.log(result);
  client.close();
}

findNearbyRestaurants();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_nearby_restaurants():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    restaurants = db.usarestaurants

    result = list(restaurants.find({
        'location': {
            '$nearSphere': {
                '$geometry': {
                    'type': 'Point',
                    'coordinates': [-122.3516, 47.6156]
                },
                '$minDistance': 1,
                '$maxDistance': 2000
            }
        }
    }, {
        'name': 1
    }))

    print(result)
    client.close()

find_nearby_restaurants()
```

------

# クエリおよびプロジェクション演算子
<a name="mongo-apis-query-projection-operators"></a>

このセクションでは、Amazon DocumentDB でサポートされているクエリ演算子と射影演算子に関する詳細情報を提供します。

**Topics**
+ [\$1](dollar-projection.md)
+ [\$1all](all.md)
+ [\$1and](and.md)
+ [\$1bitsAllClear](bitsAllClear.md)
+ [\$1bitsAllSet](bitsAllSet.md)
+ [\$1bitsAnyClear](bitsAnyClear.md)
+ [\$1bitsAnySet](bitsAnySet.md)
+ [\$1comment](comment.md)
+ [\$1elemMatch](elemMatch.md)
+ [\$1eq](eq.md)
+ [\$1exists](exists.md)
+ [\$1expr](expr.md)
+ [\$1gt](gt.md)
+ [\$1gte](gte.md)
+ [\$1in](in.md)
+ [\$1jsonSchema](jsonSchema.md)
+ [\$1lt](lt.md)
+ [\$1mod](mod-query.md)
+ [\$1lte](lte.md)
+ [\$1meta](meta.md)
+ [\$1ne](ne.md)
+ [\$1nin](nin.md)
+ [\$1nor](nor.md)
+ [\$1not](not.md)
+ [\$1or](or.md)
+ [\$1regex](regex.md)
+ [\$1slice](slice-projection.md)
+ [\$1size](size-query.md)
+ [\$1text](text.md)
+ [\$1type](type.md)

# \$1
<a name="dollar-projection"></a>

`$` 射影演算子は、配列フィールドの内容を制限して、クエリ条件に一致する最初の要素のみを返します。これは、単一の一致する配列要素を射影するために使用されます。

**パラメータ**
+ `field.$`: 位置演算子を使用して、最初に一致する要素を射影する配列フィールド。

## 例 (MongoDB シェル)
<a name="dollar-projection-examples"></a>

次の例は、`$`射影演算子を使用して一致する配列要素のみを返す方法を示しています。

**サンプルドキュメントを作成する**

```
db.students.insertMany([
  { _id: 1, name: "Alice", grades: [85, 92, 78, 95] },
  { _id: 2, name: "Bob", grades: [70, 88, 92, 65] },
  { _id: 3, name: "Charlie", grades: [95, 89, 91, 88] }
]);
```

**クエリの例**

```
db.students.find(
  { grades: { $gte: 90 } },
  { name: 1, "grades.$": 1 }
);
```

**出力**

```
{ "_id" : 1, "name" : "Alice", "grades" : [ 92 ] }
{ "_id" : 2, "name" : "Bob", "grades" : [ 92 ] }
{ "_id" : 3, "name" : "Charlie", "grades" : [ 95 ] }
```

この例では、学生ごとに 90 以上の最初のグレードのみが返されます。

## コードの例
<a name="dollar-projection-code"></a>

`$` 射影演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  const result = await collection.find(
    { grades: { $gte: 90 } },
    { projection: { name: 1, "grades.$": 1 } }
  ).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['students']

    result = list(collection.find(
        {'grades': {'$gte': 90}},
        {'name': 1, 'grades.$': 1}
    ))

    print(result)
    client.close()

example()
```

------

# \$1all
<a name="all"></a>

Amazon DocumentDB の `$all`演算子は、フィールドの値が配列であり、配列内の要素の順序に関係なく、指定されたすべての要素を含むドキュメントを一致させるために使用されます。

**パラメータ**
+ `field`: チェックするフィールドの名前。
+ `[value1, value2, ...]`: 配列内で一致する値のリスト。

 

**`$all`式`$elemMatch`内での の使用**

`$all` 式内での `$elemMatch`演算子の使用に関する制限[`$all` 式内での `$elemMatch` の使用](functional-differences.md#functional-differences.elemMatch)については、「」を参照してください。

 

**フィールド名のドル (\$1)**

ネストされたオブジェクトの `$all`の`$`プレフィックス付きフィールドのクエリに関する制限[フィールド名のドル (\$1) とドット (.)](functional-differences.md#functional-differences-dollardot)については、「」を参照してください。

## 例 (MongoDB シェル)
<a name="all-examples"></a>

次の例は、「Colors」フィールドが「Red」と「Blue」の両方を含む配列であるドキュメントを取得するために `$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`演算子は、複数の式を組み合わせて 1 つの条件として評価するために使用します。指定されたすべての式が に評価`true`された場合は が返され`true`、`false`それ以外の場合は が返されます。この演算子は、クエリに複数の条件を適用するのに役立ちます。

**パラメータ**
+ `expression1`: ブール値に評価される必須式。
+ `expression2`: ブール値に評価される必須式。
+ `...`: ブール値に評価される追加の必須式。

## 例 (MongoDB シェル)
<a name="and-examples"></a>

次の例は、 `$and`演算子を使用して、「age」フィールドが 18 より大きく、「status」フィールドが「active」である「users」コレクション内のすべてのドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
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...)、10 進数、16 進数 (0x...)、8 進数 (0o...)、またはバイナリ (BinData) 形式にすることができます。ビット位置のリストでは、最下位ビットの位置は 0 です。

## 例 (MongoDB シェル)
<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` (最下位 2 つのビット) が `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...)、10 進数、16 進数 (0x...)、8 進数 (0o...)、またはバイナリ (BinData) 形式にすることができます。ビット位置のリストでは、最下位ビットの位置は 0 です。

## 例 (MongoDB シェル)
<a name="bitsAllSet-examples"></a>

次の例は、 `$bitsAllSet`演算子を使用して、 `flags`フィールドにビットマスクで指定されたすべてのビットが設定されているドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.collection.insert([
  { _id: 1, flags: 0b1010 },
  { _id: 2, flags: 0b1100 },
  { _id: 3, flags: 0b1110 }
])
```

**クエリの例**

```
db.collection.find({ flags: { $bitsAllSet: 0b1100 } })
```

**出力**

```
{ "_id": 2, "flags": 12 },
{ "_id": 3, "flags": 14 }
```

この例では、クエリは、 `flags`フィールドにビットマスク `0b1100` (10 進値 12 を表す) で指定されたすべてのビットが設定されているドキュメントをチェックします。2 と 3 `_id` のドキュメントは、`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...)、10 進数、16 進数 (0x...)、8 進数 (0o...)、またはバイナリ (BinData) 形式にすることができます。ビット位置のリストでは、最下位ビットの位置は 0 です。

## 例 (MongoDB シェル)
<a name="bitsAnyClear-examples"></a>

次の例は、 `$bitsAnyClear`演算子を使用して、`items`コレクションの `status`フィールドでビットがクリアであるかどうかを確認する方法を示しています。

**サンプルドキュメントを作成する**

```
db.items.insertMany([
  { "_id": 1, "status": 7 },
  { "_id": 2, "status": 15 },
  { "_id": 3, "status": 31 }
]);
```

**クエリの例**

```
db.items.find({ "status": { $bitsAnyClear: 8 } })
```

**出力**

```
{ "_id" : 1, "status" : 7 }
```

この例では、クエリは、ビットマスク `8` (バイナリ ) で`status`フィールドのビットクリア (0) があるドキュメントをチェックします`1000`。(`7`バイナリ `111`) `status`の値を持つドキュメントは、指定されたビットマスクで少なくとも 1 ビットクリアであるため、クエリと一致します。一致するクリアビットは、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 ビットが 1 に設定されているドキュメントをクエリするために使用されます。この演算子を使用すると、フィールドに保存されている値に対してビット単位のオペレーションを実行できるため、ビット単位の特性を持つデータの効率的なクエリと分析が可能になります。

**パラメータ**
+ `field`: ビット単位のオペレーションを適用するフィールド名。
+ `value`: チェックするビットを指定する数値ビットマスク、またはチェックするビット位置のリスト。数値ビットマスクは、バイナリ (0b...)、10 進数、16 進数 (0x...)、8 進数 (0o...)、またはバイナリ (BinData) 形式にすることができます。ビット位置のリストでは、最下位ビットの位置は 0 です。

## 例 (MongoDB シェル)
<a name="bitsAnySet-examples"></a>

次の例は、 `$bitsAnySet`演算子を使用して、 `flags`フィールドに少なくとも 1 ビットが設定されているドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
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 }
```

クエリは、ビットマスクで指定されたビットの少なくとも 1 つが `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 シェル)
<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`演算子は、配列フィールドをクエリし、配列内の少なくとも 1 つの要素が指定された条件に一致するドキュメントを返すために使用されます。この演算子は、ネストされた配列または埋め込みドキュメントを持つ複雑なデータ構造がある場合に特に便利です。

プランナーバージョン 2.0 で のインデックスサポートが追加されました`$elemMatch`。

**パラメータ**
+ `field`: クエリする配列フィールド。
+ `query`: 配列要素と照合する基準。

 

**`$all`式`$elemMatch`内での の使用**

`$all` 式内での `$elemMatch`演算子の使用に関する制限[`$all` 式内での `$elemMatch` の使用](functional-differences.md#functional-differences.elemMatch)については、「」を参照してください。

## 例 (MongoDB シェル)
<a name="elemMatch-examples"></a>

次の例は、 `$elemMatch`演算子を使用して、`parts`配列に指定された条件に一致する要素が少なくとも 1 つあるドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.col.insertMany([
  { _id: 1, parts: [{ part: "xyz", qty: 10 }, { part: "abc", qty: 20 }] },
  { _id: 2, parts: [{ part: "xyz", qty: 5 }, { part: "abc", qty: 10 }] },
  { _id: 3, parts: [{ part: "xyz", qty: 15 }, { part: "abc", qty: 100 }] },
  { _id: 4, parts: [{ part: "abc", qty: 150 }] }
]);
```

**クエリの例**

```
db.col.find({
  parts: { "$elemMatch": { part: "xyz", qty: { $lt: 11 } } }
})
```

**出力**

```
{ "_id" : 1, "parts" : [ { "part" : "xyz", "qty" : 10 }, { "part" : "abc", "qty" : 20 } ] }
{ "_id" : 2, "parts" : [ { "part" : "xyz", "qty" : 5 }, { "part" : "abc", "qty" : 10 } ] }
```

## コードの例
<a name="elemMatch-code"></a>

`$elemMatch` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const col = db.collection('col');

  const result = await col.find({
    parts: { 
      "$elemMatch": { part: "xyz", qty: { $lt: 11 } } 
    }
  }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    col = db['col']

    result = list(col.find({
      'parts': { 
        '$elemMatch': {'part': 'xyz', 'qty': {'$lt': 11}} 
      }
    }))

    print(result)
    client.close()

example()
```

------

# \$1eq
<a name="eq"></a>

Amazon DocumentDB の `$eq`演算子は、フィールドの値が指定された値と等しいドキュメントを照合するために使用されます。この演算子は、 `find()`メソッドで一般的に使用され、指定された条件を満たすドキュメントを取得します。

**パラメータ**
+ `field` : 等価条件をチェックするフィールド。
+ `value` : フィールドと比較する値。

## 例 (MongoDB シェル)
<a name="eq-examples"></a>

次の例は、 `$eq`演算子を使用して、 `name`フィールドが と等しいすべてのドキュメントを検索する方法を示しています`"Thai Curry Palace"`。

**サンプルドキュメントを作成する**

```
db.restaurants.insertMany([
  { name: "Thai Curry Palace", cuisine: "Thai", features: ["Private Dining"] },
  { name: "Italian Bistro", cuisine: "Italian", features: ["Outdoor Seating"] },
  { name: "Mexican Grill", cuisine: "Mexican", features: ["Takeout"] }
]);
```

**クエリの例**

```
db.restaurants.find({ name: { $eq: "Thai Curry Palace" } });
```

**出力**

```
{ "_id" : ObjectId("68ee586f916df9d39f3d9414"), "name" : "Thai Curry Palace", "cuisine" : "Thai", "features" : [ "Private Dining" ] }
```

## コードの例
<a name="eq-code"></a>

`$eq` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findByName(name) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('restaurants');

  const results = await collection.find({ name: { $eq: name } }).toArray();
  console.log(results);

  await client.close();
}

findByName("Thai Curry Palace");
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_by_name(name):
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    collection = db["restaurants"]

    results = list(collection.find({ "name": { "$eq": name } }))
    print(results)

    client.close()

find_by_name("Thai Curry Palace")
```

------

# \$1exists
<a name="exists"></a>

`$exists` 演算子は、フィールドがドキュメントに存在するかどうかをチェックするために使用されます。`$exists`特に、インデックス付きフィールドがすべてのドキュメントに存在するわけではない Amazon DocumentDB でスパースインデックスを操作する場合に便利です。

クエリで作成したスパースなインデックスを使用するには、インデックスをカバーするフィールドで `$exists` 句を使用する必要があります。を省略した場合`$exists`、Amazon DocumentDB はクエリにスパースインデックスを使用しません。

**パラメータ**
+ `field`: 存在を確認するフィールド名。
+ `value`: フィールドが一致するドキュメントに存在する (`true``false`) か存在しない (`true`) かを指定するブール値 ( または `false`)。

## 例 (MongoDB シェル)
<a name="exists-examples"></a>

次の例は、`food`コレクション内の `special_diets`フィールドでスパースインデックスを持つ `$exists`演算子の使用を示しています。

**サンプルドキュメントを作成する**

```
db.food.insertMany([
  { _id: 1, name: "Apple", special_diets: ["vegetarian", "gluten-free"] },
  { _id: 2, name: "Broccoli" },
  { _id: 3, name: "Chicken", special_diets: ["dairy-free"] }
]);
```

**「special\$1diets」フィールドにスパースインデックスを作成する**

```
db.food.createIndex({ "special_diets": 1 }, { sparse: true, name: "special_diets_sparse_asc" });
```

**クエリの例**

```
db.food.find({ "special_diets": { $exists: true } });
```

**出力**

```
[
  { "_id" : 1, "name" : "Apple", "special_diets" : [ "vegetarian", "gluten-free" ] },
  { "_id" : 3, "name" : "Chicken", "special_diets" : [ "dairy-free" ] }
]
```

## コードの例
<a name="exists-code"></a>

`$exists` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('food');

  const result = await collection.find({ "special_diets": { $exists: true } }).toArray();
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
import pymongo

client = pymongo.MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['food']

result = list(collection.find({"special_diets": {"$exists": True}}))
print(result)

client.close()
```

------

# \$1expr
<a name="expr"></a>

バージョン 4.0 の新機能。

Elastic クラスターではサポートされていません。

Amazon DocumentDB の `$expr`演算子を使用すると、クエリ言語内で集計式を使用できます。これにより、集約パイプラインステージを使用する方法と同様に、ドキュメント内のフィールドに対して複雑な比較と計算を実行できます。

**パラメータ**
+ `expression`: ブール値を返す式。ドキュメントフィールドで比較と計算を実行できます。

## 例 (MongoDB シェル)
<a name="expr-examples"></a>

次の例は、 `$expr`演算子を使用して、 `manufacturingCost`フィールドが `price`フィールドより大きいすべてのドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.inventory.insertMany([
  { item: "abc", manufacturingCost: 500, price: 100 },
  { item: "def", manufacturingCost: 300, price: 450 },
  { item: "ghi", manufacturingCost: 400, price: 120 }
]);
```

**クエリの例**

```
db.inventory.find({
  $expr: {
    $gt: ["$manufacturingCost", "$price"]
  }
})
```

**出力**

```
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89a"), "item" : "abc", "manufacturingCost" : 500, "price" : 100 },
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89c"), "item" : "ghi", "manufacturingCost" : 400, "price" : 120 }
```

## コードの例
<a name="expr-code"></a>

`$expr` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.find({
    $expr: {
      $gt: ['$manufacturingCost', '$price']
    }
  }).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.find({
        '$expr': {
            '$gt': ['$manufacturingCost', '$price']
        }
    }))

    print(result)
    client.close()

example()
```

------

# \$1gt
<a name="gt"></a>

Amazon DocumentDB の `$gt`演算子は、指定されたフィールドの値が指定された値より大きいドキュメントを選択するために使用されます。この演算子は、数値比較に基づいてデータをフィルタリングおよびクエリするのに役立ちます。

**パラメータ**
+ `field`: 比較するフィールド。
+ `value`: 比較する値。

## 例 (MongoDB シェル)
<a name="gt-examples"></a>

次の例は、 `$gt`演算子を使用して、 `age`フィールドが 30 より大きいすべてのドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { name: "John", age: 25 },
  { name: "Jane", age: 32 },
  { name: "Bob", age: 45 },
  { name: "Alice", age: 28 }
]);
```

**クエリの例**

```
db.users.find({ age: { $gt: 30 } });
```

**出力**

```
{ "_id" : ObjectId("6249e5c22a5d39884a0a0001"), "name" : "Jane", "age" : 32 },
{ "_id" : ObjectId("6249e5c22a5d39884a0a0002"), "name" : "Bob", "age" : 45 }
```

## コードの例
<a name="gt-code"></a>

`$gt` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findUsersOlderThan30() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = await db.collection('users').find({ age: { $gt: 30 } }).toArray();
  console.log(users);
  await client.close();
}

findUsersOlderThan30();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_users_older_than_30():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    users = list(db.users.find({ 'age': { '$gt': 30 } }))
    print(users)
    client.close()

find_users_older_than_30()
```

------

# \$1gte
<a name="gte"></a>

Amazon DocumentDB の `$gte`演算子は、指定された値以上の値を一致させるために使用されます。この演算子は、数値比較に基づいてデータをフィルタリングおよびクエリするのに役立ちます。

**パラメータ**
+ `field`: 指定された値と照合するフィールド。
+ `value`: フィールドと比較する値。

## 例 (MongoDB シェル)
<a name="gte-examples"></a>

次の例は、Amazon DocumentDB で `$gte`演算子を使用して、「age」フィールドが 25 以上であるすべてのドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { _id: 1, name: "John", age: 20 },
  { _id: 2, name: "Jane", age: 25 },
  { _id: 3, name: "Bob", age: 30 },
  { _id: 4, name: "Alice", age: 35 }
]);
```

**クエリの例**

```
db.users.find({ age: { $gte: 25 } }, { _id: 0, name: 1, age: 1 });
```

**出力**

```
{ "name" : "Jane", "age" : 25 }
{ "name" : "Bob", "age" : 30 }
{ "name" : "Alice", "age" : 35 }
```

## コードの例
<a name="gte-code"></a>

`$gte` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findUsersAboveAge(age) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.find({ age: { $gte: age } }, { projection: { _id: 0, name: 1, age: 1 } }).toArray();
  console.log(result);

  await client.close();
}

findUsersAboveAge(25);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_users_above_age(age):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    users = db.users

    result = list(users.find({ 'age': { '$gte': age } }, { '_id': 0, 'name': 1, 'age': 1 }))
    print(result)

    client.close()

find_users_above_age(25)
```

------

# \$1in
<a name="in"></a>

Amazon DocumentDB の `$in`演算子は、フィールドの値が配列で指定された値のいずれかと等しいドキュメントを検索できる論理クエリ演算子です。

**パラメータ**
+ `field`: 指定された配列と照合するフィールド。
+ `[value1, value2, ...]`: 指定されたフィールドに一致する値の配列。

 

**フィールド名のドル (`$`)**

ネストされたオブジェクトの `$in`の`$`プレフィックス付きフィールドのクエリに関する制限[フィールド名のドル (\$1) とドット (.)](functional-differences.md#functional-differences-dollardot)については、「」を参照してください。

## 例 (MongoDB シェル)
<a name="in-examples"></a>

次の例は、 `$in`演算子を使用して、 `color`フィールドが指定された配列の値の 1 つであるドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
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 シェル)
<a name="jsonSchema-examples"></a>

次の例は、 `$jsonSchema`演算子を使用して`employees`コレクションをフィルタリングし`name`、 フィールド、 `age`フィールド、`employeeId`および フィールドを持つドキュメントのみを取得する方法を示しています。 `employeeId`フィールドのタイプは です`string`。

**サンプルドキュメントを作成する**

```
db.employees.insertMany([
  { "name": { "firstName": "Carol", "lastName": "Smith" }, "employeeId": "1" },
  { "name": { "firstName": "Emily", "lastName": "Brown" }, "employeeId": "2", "age": 25 },
  { "name": { "firstName": "William", "lastName": "Taylor" }, "employeeId": 3, "age": 24 },
  { "name": { "firstName": "Jane", "lastName": "Doe" }, "employeeId": "4" }
]);
```

**クエリの例**

```
db.employees.aggregate([
  { $match: {
    $jsonSchema: {
      required: ["name", "employeeId", "age"],
      properties: { "employeeId": { "bsonType": "string" } }
    }
  }}
]);
```

**出力**

```
{ "_id" : ObjectId("6908e8b61f77fc26b2ecd26f"), "name" : { "firstName" : "Emily", "lastName" : "Brown" }, "employeeId" : "2", "age" : 25 }
```

## コードの例
<a name="jsonSchema-code"></a>

`$jsonSchema` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function filterByJsonSchema() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('employees');

  const result = await collection.aggregate([
    {
      $match: {
        $jsonSchema: {
          required: ['name', 'employeeId', 'age'],
          properties: { 'employeeId': { 'bsonType': 'string' } }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

filterByJsonSchema();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def filter_by_json_schema():
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
  db = client['test']
  collection = db['employees']

  result = list(collection.aggregate([
    {
      '$match': {
        '$jsonSchema': {
          'required': ['name', 'employeeId', 'age'],
          'properties': {'employeeId': {'bsonType': 'string'}}
        }
      }
    }
  ]))

  print(result)
  client.close()

filter_by_json_schema()
```

------

# \$1lt
<a name="lt"></a>

Amazon DocumentDB の `$lt`演算子は、指定された値より小さい値を一致させるために使用されます。この演算子は、数値比較に基づいてデータをフィルタリングおよびクエリするのに役立ちます。

**パラメータ**
+ `field`: 確認するフィールド名。
+ `value`: 比較する値。

## 例 (MongoDB シェル)
<a name="lt-examples"></a>

次の例は、 `$lt`演算子を使用して、`Inventory.OnHand`値が 50 未満のドキュメントを取得する方法を示しています。

**サンプルドキュメントを作成する**

```
db.example.insertMany([
  { "_id": 1, "Inventory": { "OnHand": 25, "Sold": 60 }, "Colors": ["Red", "Blue"] },
  { "_id": 2, "Inventory": { "OnHand": 75, "Sold": 40 }, "Colors": ["Red", "White"] },
  { "_id": 3, "Inventory": { "OnHand": 10, "Sold": 85 }, "Colors": ["Red", "Green"] }
]);
```

**クエリの例**

```
db.example.find({ "Inventory.OnHand": { $lt: 50 } })
```

**出力**

```
{ "_id" : 1, "Inventory" : { "OnHand" : 25, "Sold" : 60 }, "Colors" : [ "Red", "Blue" ] }
{ "_id" : 3, "Inventory" : { "OnHand" : 10, "Sold" : 85 }, "Colors" : [ "Red", "Green" ] }
```

## コードの例
<a name="lt-code"></a>

`$lt` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  const result = await collection.find({ "Inventory.OnHand": { $lt: 50 } }).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    result = list(collection.find({ "Inventory.OnHand": { "$lt": 50 } }))
    print(result)

    client.close()

example()
```

------

# \$1mod
<a name="mod-query"></a>

`$mod` クエリ演算子は、フィールド値を除数で割ったドキュメントに指定された余りがあるドキュメントを選択します。これは、モジュロ算術条件に基づいてドキュメントをフィルタリングする場合に便利です。

**パラメータ**
+ `divisor`: 除算する数値。
+ `remainder`: 予想される余剰値。

## 例 (MongoDB シェル)
<a name="mod-query-examples"></a>

次の例は、 `$mod`演算子を使用して、数量が奇数であるすべての注文を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.orders.insertMany([
  { _id: 1, item: "Widget", quantity: 15 },
  { _id: 2, item: "Gadget", quantity: 20 },
  { _id: 3, item: "Tool", quantity: 7 },
  { _id: 4, item: "Device", quantity: 12 },
  { _id: 5, item: "Part", quantity: 9 }
]);
```

**クエリの例**

```
db.orders.find({ quantity: { $mod: [2, 1] } });
```

**出力**

```
{ "_id" : 1, "item" : "Widget", "quantity" : 15 }
{ "_id" : 3, "item" : "Tool", "quantity" : 7 }
{ "_id" : 5, "item" : "Part", "quantity" : 9 }
```

このクエリは、数量を 2 で割ったドキュメントの残りが 1 で、すべての奇数を効果的に選択します。

## コードの例
<a name="mod-query-code"></a>

`$mod` クエリ演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.find({ quantity: { $mod: [2, 1] } }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.find({'quantity': {'$mod': [2, 1]}}))

    print(result)
    client.close()

example()
```

------

# \$1lte
<a name="lte"></a>

Amazon DocumentDB の `$lte`演算子は、指定されたフィールドの値が指定された値以下であるドキュメントを一致させるために使用されます。この演算子は、数値比較に基づいてデータをフィルタリングおよびクエリするのに役立ちます。

**パラメータ**
+ `field`: 比較するフィールド。
+ `value`: 比較する値。

## 例 (MongoDB シェル)
<a name="lte-examples"></a>

次の例は、 `$lte` 演算子を使用して、 `quantity`フィールドが 10 以下のドキュメントを取得する方法を示しています。

**サンプルドキュメントを作成する**

```
db.inventory.insertMany([
  { item: "canvas", qty: 100 },
  { item: "paint", qty: 50 },
  { item: "brush", qty: 10 },
  { item: "paper", qty: 5 }
]);
```

**クエリの例**

```
db.inventory.find({ qty: { $lte: 10 } });
```

**出力**

```
{ "_id" : ObjectId("..."), "item" : "brush", "qty" : 10 },
{ "_id" : ObjectId("..."), "item" : "paper", "qty" : 5 }
```

## コードの例
<a name="lte-code"></a>

`$lte` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db("test");
  const collection = db.collection("inventory");

  const result = await collection.find({ qty: { $lte: 10 } }).toArray();
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client["test"]
    collection = db["inventory"]

    result = list(collection.find({ "qty": { "$lte": 10 } }))
    print(result)

    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1meta
<a name="meta"></a>

`$meta` 演算子は、現在のクエリ実行に関連付けられたメタデータにアクセスするために使用されます。この演算子は主にテキスト検索オペレーションに使用されます。メタデータは、一致したドキュメントの関連性に関する情報を提供します。

**パラメータ**
+ `textScore`: ドキュメントのテキスト検索スコアを取得します。このスコアは、ドキュメントとテキスト検索クエリの関連性を示します。

## 例 (MongoDB シェル)
<a name="meta-examples"></a>

次の例は、 `$meta`演算子を使用して、テキスト検索クエリに一致するドキュメントのテキスト検索スコアを取得する方法を示しています。

**サンプルドキュメントを作成する**

```
db.documents.insertMany([
  { _id: 1, title: "Coffee Basics", content: "Coffee is a popular beverage made from roasted coffee beans." },
  { _id: 2, title: "Coffee Culture", content: "Coffee coffee coffee - the ultimate guide to coffee brewing and coffee preparation." },
  { _id: 3, title: "Tea vs Coffee", content: "Many people prefer tea over coffee for its health benefits." }
]);
```

**テキストインデックスを作成する**

```
db.documents.createIndex({ content: "text" });
```

**クエリの例**

```
db.documents.find(
  { $text: { $search: "coffee" } },
  { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });
```

**出力**

```
[
  {
    title: 'Coffee Culture',
    content: 'Coffee coffee coffee - the ultimate guide to coffee brewing and coffee preparation.',
    score: 0.8897688388824463
  },
  {
    title: 'Coffee Basics',
    content: 'Coffee is a popular beverage made from roasted coffee beans.',
    score: 0.75990891456604
  },
  {
    title: 'Tea vs Coffee',
    content: 'Many people prefer tea over coffee for its health benefits.',
    score: 0.6079270839691162
  }
]
```

## コードの例
<a name="meta-code"></a>

`$meta` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findWithTextScore() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('documents');

  const result = await collection.find(
    { $text: { $search: "coffee" } },
    { projection: { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } } }
  ).sort({ score: { $meta: "textScore" } }).toArray();

  console.log(result);
  client.close();
}

findWithTextScore();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['documents']

for doc in collection.find(
    {'$text': {'$search': 'coffee'}},
    {'_id': 0, 'title': 1, 'content': 1, 'score': {'$meta': 'textScore'}}
).sort([('score', {'$meta': 'textScore'})]):
    print(doc)

client.close()
```

------

# \$1ne
<a name="ne"></a>

`$ne` 演算子は、フィールドの値が指定された値と等しくないドキュメントを一致させるために使用されます。これは、クエリ述語でドキュメントをフィルタリングするために使用できる比較演算子です。

プランナーバージョン 2.0 で のインデックスサポートが追加されました`$ne`。

**パラメータ**
+ `field`: 確認するフィールド。
+ `value`: チェックする値。

## 例 (MongoDB シェル)
<a name="ne-examples"></a>

この例では、 `status`フィールドが と等しくないすべてのドキュメントが`users`コレクションにあります`"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`: チェックする値の配列。

 

**フィールド名のドル (`$`)**

ネストされたオブジェクトの `$nin`の`$`プレフィックス付きフィールドのクエリに関する制限[フィールド名のドル (\$1) とドット (.)](functional-differences.md#functional-differences-dollardot)については、「」を参照してください。

## 例 (MongoDB シェル)
<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` 演算子は、指定されたクエリ条件のいずれにも当てはまらないドキュメントを一致させるために使用されます。これは論理的な「NOR」オペレーションに似ています。いずれのオペランドも true でない場合、結果は true になります。

**パラメータ**
+ `expression1`: 評価する最初の式。
+ `expression2`: 評価する 2 番目の式。
+ `expressionN`: 評価する追加の式。

## 例 (MongoDB シェル)
<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 シェル)
<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` 演算子は、2 つ以上の式の配列に対して論理 OR オペレーションを実行するために使用されます。少なくとも 1 つの式に一致するドキュメントを返します。この演算子は、複数の条件のいずれかを満たすドキュメントをクエリする必要がある場合に便利です。

**パラメータ**
+ `expression1`: 評価する最初の式。
+ `expression2`: 評価する 2 番目の式。
+ `...`: 評価する追加の式 (オプション）。

## 例 (MongoDB シェル)
<a name="or-examples"></a>

次の例は、 がモデル「Heavy H1」のTruckForYou」またはモデル「Bolid 1」のSportForYou`make`」のいずれかであるドキュメントを検索する`$or`演算子の使用を示しています。

**サンプルドキュメントを作成する**

```
db.cars.insertMany([
  { make: "TruckForYou", model: "Heavy H1", year: 2020 },
  { make: "SportForYou", model: "Bolid 1", year: 2021 },
  { make: "TruckForYou", model: "Cargo 5", year: 2019 },
  { make: "SportForYou", model: "Racer 2", year: 2022 }
]);
```

**クエリの例**

```
db.cars.find({
  $or: [
    { make: "TruckForYou", model: "Heavy H1" },
    { make: "SportForYou", model: "Bolid 1" }
  ]
});
```

**出力**

```
[
  {
    _id: ObjectId('...'),
    make: 'TruckForYou',
    model: 'Heavy H1',
    year: 2020
  },
  {
    _id: ObjectId('...'),
    make: 'SportForYou',
    model: 'Bolid 1',
    year: 2021
  }
]
```

## コードの例
<a name="or-code"></a>

`$or` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findCarsByMakeModel() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const cars = db.collection('cars');

  const result = await cars.find({
    $or: [
      { make: "TruckForYou", model: "Heavy H1" },
      { make: "SportForYou", model: "Bolid 1" }
    ]
  }).toArray();

  console.log(result);
  client.close();
}

findCarsByMakeModel();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_cars_by_make_model():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    cars = db.cars

    result = list(cars.find({
        '$or': [
            {'make': 'TruckForYou', 'model': 'Heavy H1'},
            {'make': 'SportForYou', 'model': 'Bolid 1'}
        ]
    }))

    print(result)
    client.close()

find_cars_by_make_model()
```

------

# \$1regex
<a name="regex"></a>

`$regex` 演算子を使用すると、文字列フィールドで正規表現マッチングを実行できます。これは、複雑なパターンに基づいてドキュメントを検索およびフィルタリングするための強力なツールです。

**パラメータ**
+ `regular expression`: フィールドに一致する正規表現パターン。
+ `$options`: (オプション) 大文字と小文字の区別、グローバルマッチングなど、検索動作を変更するオプションを提供します。

## 例 (MongoDB シェル)
<a name="regex-examples"></a>

次の例は、「name」フィールドが特定のパターンに一致するドキュメントを検索するための `$regex`演算子の使用を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { name: "John Doe" },
  { name: "Jane Smith" },
  { name: "Alice Johnson" },
  { name: "Bob Williams" },
  { name: "Charlie Davis" }
]);
```

**クエリの例**

```
db.users.find({ name: { $regex: /^A/ } })
```

**出力**

```
[
  { "_id" : ObjectId("..."), "name" : "Alice Johnson" }
]
```

このクエリは、「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 シェル)
<a name="slice-projection-examples"></a>

次の例は、`$slice`射影演算子を使用して配列フィールドから最初の 2 つの項目のみを返す方法を示しています。

**サンプルドキュメントを作成する**

```
db.inventory.insertMany([
  { _id: 1, item: "notebook", tags: ["office", "school", "supplies", "writing"] },
  { _id: 2, item: "pen", tags: ["office", "writing"] },
  { _id: 3, item: "folder", tags: ["office", "supplies", "storage", "organization"] }
]);
```

**クエリの例**

```
db.inventory.find(
  {},
  { item: 1, tags: { $slice: 2 } }
)
```

**出力**

```
{ "_id" : 1, "item" : "notebook", "tags" : [ "office", "school" ] }
{ "_id" : 2, "item" : "pen", "tags" : [ "office", "writing" ] }
{ "_id" : 3, "item" : "folder", "tags" : [ "office", "supplies" ] }
```

## コードの例
<a name="slice-projection-code"></a>

`$slice` 射影演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.find(
    {},
    { projection: { item: 1, tags: { $slice: 2 } } }
  ).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.find(
        {},
        {'item': 1, 'tags': {'$slice': 2}}
    ))

    print(result)
    client.close()

example()
```

------

# \$1size
<a name="size-query"></a>

`$size` クエリ演算子は、配列フィールドの要素数が正確に指定された数であるドキュメントに一致します。これは、配列の長さに基づいてドキュメントをフィルタリングするのに役立ちます。

**パラメータ**
+ `field`: 確認する配列フィールド。
+ `count`: 配列に含める必要がある要素の正確な数。

## 例 (MongoDB シェル)
<a name="size-query-examples"></a>

次の例は、 `$size`演算子を使用して、厳密に 3 つのタグを持つすべての製品を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", tags: ["electronics", "computers", "portable"] },
  { _id: 2, name: "Mouse", tags: ["electronics", "accessories"] },
  { _id: 3, name: "Desk", tags: ["furniture", "office", "workspace"] },
  { _id: 4, name: "Monitor", tags: ["electronics"] }
]);
```

**クエリの例**

```
db.products.find({ tags: { $size: 3 } });
```

**出力**

```
{ "_id" : 1, "name" : "Laptop", "tags" : [ "electronics", "computers", "portable" ] }
{ "_id" : 3, "name" : "Desk", "tags" : [ "furniture", "office", "workspace" ] }
```

## コードの例
<a name="size-query-code"></a>

`$size` クエリ演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.find({ tags: { $size: 3 } }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.find({'tags': {'$size': 3}}))

    print(result)
    client.close()

example()
```

------

# \$1text
<a name="text"></a>

`$text` 演算子は、ドキュメントコレクション内のテキストインデックス付きフィールドに対して全文検索を実行するために使用されます。この演算子を使用すると、特定の単語やフレーズを含むドキュメントを検索し、他のクエリ演算子と組み合わせて、追加の条件に基づいて結果をフィルタリングできます。

**パラメータ**
+ `$search`: 検索するテキスト文字列。

## 例 (MongoDB シェル)
<a name="text-examples"></a>

次の例は、 `$text`演算子を使用して「interest」という単語を含むドキュメントを検索し、「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" }
```

上記のコマンドは、任意の形式の「interest」と 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 シェル)
<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 シェル)
<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 シェル)
<a name="dollarBrackets-update-examples"></a>

次の例は、 `$[]`演算子を使用してすべての配列要素を更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertOne({
  _id: 1,
  name: "Laptop",
  prices: [1000, 1100, 1200]
});
```

**クエリの例**

```
db.products.updateOne(
  { _id: 1 },
  { $inc: { "prices.$[]": 50 } }
);
```

**出力**

```
{
  "_id" : 1,
  "name" : "Laptop",
  "prices" : [ 1050, 1150, 1250 ]
}
```

## コードの例
<a name="dollarBrackets-update-code"></a>

`$[]` 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  await collection.updateOne(
    { _id: 1 },
    { $inc: { "prices.$[]": 50 } }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    collection.update_one(
        {'_id': 1},
        {'$inc': {'prices.$[]': 50}}
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1[<identifier>]
<a name="dollarIdentifier-update"></a>

`$[<identifier>]` フィルタリングされた位置演算子は、指定されたフィルター条件に一致するすべての配列要素を更新します。これは、配列要素を選択的に更新する `arrayFilters`オプションとともに使用されます。

**パラメータ**
+ `field.$[identifier]`: フィルタリングされた位置演算子を持つ配列フィールド。
+ `arrayFilters`: 更新する要素を決定するフィルター条件の配列。

## 例 (MongoDB シェル)
<a name="dollarIdentifier-update-examples"></a>

次の例は、 `$[<identifier>]`演算子を使用して、条件に基づいて特定の配列要素を更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  grades: [
    { subject: "Math", score: 85 },
    { subject: "Science", score: 92 },
    { subject: "History", score: 78 }
  ]
});
```

**クエリの例**

```
db.students.updateOne(
  { _id: 1 },
  { $inc: { "grades.$[elem].score": 5 } },
  { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
);
```

**出力**

```
{
  "_id" : 1,
  "name" : "Alice",
  "grades" : [
    { "subject" : "Math", "score" : 90 },
    { "subject" : "Science", "score" : 97 },
    { "subject" : "History", "score" : 78 }
  ]
}
```

## コードの例
<a name="dollarIdentifier-update-code"></a>

`$[<identifier>]` 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  await collection.updateOne(
    { _id: 1 },
    { $inc: { "grades.$[elem].score": 5 } },
    { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.students

    collection.update_one(
        {'_id': 1},
        {'$inc': {'grades.$[elem].score': 5}},
        array_filters=[{'elem.score': {'$gte': 80}}]
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1addToSet
<a name="addToSet"></a>

Amazon DocumentDB の `$addToSet`演算子は、値が配列にまだ存在しない場合にのみ、配列に値を追加するために使用されます。これは、配列に一意の要素が含まれていることを確認するのに役立ちます。

**パラメータ**
+ `field`: 更新するフィールド。
+ `value`: 配列フィールドに追加する値。これは単一の値でも式でもかまいません。

## 例 (MongoDB シェル)
<a name="addToSet-examples"></a>

次の例は、 `$addToSet`演算子を使用して配列に一意の要素を追加する方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertMany([
  { "_id": 1, "item": "apple", "tags": ["fruit", "red", "round"] },
  { "_id": 2, "item": "banana", "tags": ["fruit", "yellow"] },
  { "_id": 3, "item": "cherry", "tags": ["fruit", "red"] }
])
```

**クエリの例**

```
db.products.update(
  { "item": "apple" },
  { $addToSet: { "tags": "green" } }
)
```

**出力**

```
{ "_id": 1, "item": "apple", "tags": ["fruit", "red", "round", "green"] }
```

この例では、`$addToSet`演算子は「item」フィールドが「apple」であるドキュメントの「tags」配列に「green」タグを追加します。「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 シェル)
<a name="bit-examples"></a>

次の例は、 `$bit`演算子を使用して数値フィールドに対してビット単位のオペレーションを実行する方法を示しています。

**サンプルドキュメントを作成する**

```
db.numbers.insert([
  { "_id": 1, "number": 5 },
  { "_id": 2, "number": 12 }
])
```

**クエリの例**

```
db.numbers.update(
  { "_id": 1 },
  { "$bit": { "number": { "and": 3 } } }
)
```

**出力**

```
{
  "_id": 1,
  "number": 1
}
```

この例では、 `$bit`演算子を使用して、 が 1 のドキュメントの「数値」フィールドに対してビット単位`_id`の AND オペレーションを実行します。その結果、「数値」フィールドの値は 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 シェル)
<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`、配列フィールドに複数の値を追加します。これにより、複数の更新オペレーションを実行するのではなく、1 回のオペレーションで配列に複数の要素を追加できます。

**パラメータ**
+ `value`: 配列フィールドに追加する値の配列。

## 例 (MongoDB シェル)
<a name="each-examples"></a>

次の例は、 `$each`演算子と `$push`演算子を使用して、配列フィールドに複数の要素を追加する方法を示しています。

**サンプルドキュメントを作成する**

```
db.fruits.insertOne({
  _id: 1,
  fruits: ["apple", "banana"]
})
```

**クエリの例**

```
db.fruits.updateOne(
  { _id: 1 },
  { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
)
```

**更新されたドキュメントを表示する**

```
db.fruits.findOne({ _id: 1 })
```

**出力**

```
{
  _id: 1,
  fruits: [ 'apple', 'banana', 'cherry', 'durian', 'elderberry' ]
}
```

## コードの例
<a name="each-code"></a>

`$each` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('fruits');

  await collection.updateOne(
    { _id: 1 },
    { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
  );

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['fruits']

    collection.update_one(
        {'_id': 1},
        {'$push': {'fruits': {'$each': ['cherry', 'durian', 'elderberry']}}}
    )

    client.close()

example()
```

------

# \$1inc
<a name="inc"></a>

`$inc` 演算子は、フィールドの値を指定された量だけ増分するために使用されます。カウンターやレーティングなどの数値フィールドを更新するために使用され、現在の値を取得したり、新しい値を計算したり、フィールドを更新したりする必要はありません。

**パラメータ**
+ `field`: 増分するフィールドの名前。
+ `amount`: フィールドをインクリメントする量。これは正の値でも負の値でもかまいません。

## 例 (MongoDB シェル)
<a name="inc-examples"></a>

次の例は、 `$inc`演算子を使用してドキュメントの `age`フィールドをインクリメントする方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertOne({_id: 123, name: "John Doe", age: 30})
```

**クエリの例**

```
db.users.updateOne({_id: 123}, {$inc: {age: 1}})
```

**更新されたドキュメントを表示する**

```
db.users.findOne({_id: 123})
```

**出力**

```
{ "_id" : 123, "name" : "John Doe", "age" : 31 }
```

## コードの例
<a name="inc-code"></a>

`$inc` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateWithInc() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.updateOne(
    { _id: 123 },
    { $inc: { age: 1 } }
  );

  console.log(result);

  await client.close();
}

updateWithInc();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_with_inc():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    result = collection.update_one(
        {'_id': 123},
        {'$inc': {'age': 1}}
    )

    print(result.modified_count)

    client.close()

update_with_inc()
```

------

# \$1max
<a name="max-update"></a>

`$max` 更新演算子は、指定された値が現在のフィールド値より大きい場合にのみ、フィールドの値を更新します。この演算子は、更新全体で最大値を維持するのに役立ちます。

**パラメータ**
+ `field`: 更新するフィールド。
+ `value`: 現在のフィールド値と比較する値。

## 例 (MongoDB シェル)
<a name="max-update-examples"></a>

次の例は、 `$max`演算子を使用してプレイヤーの記録された最高スコアを更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.scores.insertMany([
  { _id: 1, player: "Alice", highScore: 85 },
  { _id: 2, player: "Bob", highScore: 92 },
  { _id: 3, player: "Charlie", highScore: 78 }
])
```

**更新の例**

```
db.scores.updateOne(
  { _id: 1 },
  { $max: { highScore: 95 } }
)
```

**結果**

Alice の `highScore`フィールドは、95 が現在の値である 85 より大きいため、95 に更新されます。

```
{ "_id": 1, "player": "Alice", "highScore": 95 }
```

## コードの例
<a name="max-update-code"></a>

`$max` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('scores');

  const result = await collection.updateOne(
    { _id: 1 },
    { $max: { highScore: 95 } }
  );

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['scores']

    result = collection.update_one(
        { '_id': 1 },
        { '$max': { 'highScore': 95 } }
    )

    print(result)
    client.close()

example()
```

------

# \$1min
<a name="min-update"></a>

`$min` 更新演算子は、指定された値が現在のフィールド値より小さい場合にのみ、フィールドの値を更新します。この演算子は、更新全体で最小値を維持するのに役立ちます。

**パラメータ**
+ `field`: 更新するフィールド。
+ `value`: 現在のフィールド値と比較する値。

## 例 (MongoDB シェル)
<a name="min-update-examples"></a>

次の例は、 `$min`演算子を使用して気象観測所の記録された最低温度を更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.weather.insertMany([
  { _id: 1, station: "Station A", lowestTemp: 15 },
  { _id: 2, station: "Station B", lowestTemp: 20 },
  { _id: 3, station: "Station C", lowestTemp: 18 }
])
```

**更新の例**

```
db.weather.updateOne(
  { _id: 1 },
  { $min: { lowestTemp: 12 } }
)
```

**結果**

ステーション A の `lowestTemp`フィールドは、12 が現在の値である 15 より小さいため、12 に更新されます。

```
{ "_id": 1, "station": "Station A", "lowestTemp": 12 }
```

## コードの例
<a name="min-update-code"></a>

`$min` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('weather');

  const result = await collection.updateOne(
    { _id: 1 },
    { $min: { lowestTemp: 12 } }
  );

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['weather']

    result = collection.update_one(
        { '_id': 1 },
        { '$min': { 'lowestTemp': 12 } }
    )

    print(result)
    client.close()

example()
```

------

# \$1mul
<a name="mul"></a>

Amazon DocumentDB の `$mul`演算子は、フィールドの値を指定された数で乗算するために使用されます。これは、クレジットカードのステータスに基づいてフライトマイルを更新するなど、複数のドキュメントをアトミックかつ一貫して更新する場合に便利です。

**パラメータ**
+ `field`: 乗算するフィールド。
+ `multiplier`: フィールド値に乗算する数値。

## 例 (MongoDB シェル)
<a name="mul-examples"></a>

この例では、 `$mul`演算子を使用して、 `credit_card`フィールドが であるすべてのドキュメントの`flight_miles`値を 2 倍にする方法を示します`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 ] }
```

クレジットカードをお持ちのお客様には、フライトマイルが 2 倍になりました。

`$[]` 位置配列演算子は、`flight_miles`配列内の各要素に`$mul`オペレーションを適用するために使用されます。

## コードの例
<a name="mul-code"></a>

`$mul` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateFlightMiles() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  await collection.updateMany(
    { credit_card: true },
    { $mul: { 'flight_miles.$[]': 2 } }
  );

  const documents = await collection.find().toArray();
  console.log(documents);

  await client.close();
}

updateFlightMiles();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_flight_miles():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.miles

    collection.update_many(
        {'credit_card': True},
        {'$mul': {'flight_miles.$[]': 2}}
    )

    documents = list(collection.find())
    print(documents)

    client.close()

update_flight_miles()
```

------

# \$1pop
<a name="pop"></a>

Amazon DocumentDB の `$pop`演算子は、配列フィールドから最初または最後の要素を削除するために使用されます。これは、固定サイズの配列を維持したり、ドキュメント内にキューのようなデータ構造を実装する必要がある場合に特に便利です。

**パラメータ**
+ `field`: 要素を削除する配列フィールドの名前。
+ `value`: 削除する要素の位置を決定する整数値。の値は最後の要素`1`を削除し、 の値は最初の要素`-1`を削除します。

## 例 (MongoDB シェル)
<a name="pop-examples"></a>

この例では、 `$pop`演算子を使用して配列フィールドから最初と最後の要素を削除する方法を示します。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming", "hiking"] },
  { "_id": 2, "name": "Jane Smith", "hobbies": ["cooking", "gardening", "painting"] }
])
```

**クエリの例**

```
// Remove the first element from the "hobbies" array
db.users.update({ "_id": 1 }, { $pop: { "hobbies": -1 } })

// Remove the last element from the "hobbies" array
db.users.update({ "_id": 2 }, { $pop: { "hobbies": 1 } })
```

**出力**

```
{ "_id" : 1, "name" : "John Doe", "hobbies" : [ "swimming", "hiking" ] }
{ "_id" : 2, "name" : "Jane Smith", "hobbies" : [ "cooking", "gardening" ] }
```

## コードの例
<a name="pop-code"></a>

`$pop` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  // Remove the first element from the "hobbies" array
  await collection.updateOne({ "_id": 1 }, { $pop: { "hobbies": -1 } });

  // Remove the last element from the "hobbies" array
  await collection.updateOne({ "_id": 2 }, { $pop: { "hobbies": 1 } });

  const users = await collection.find().toArray();
  console.log(users);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    # Remove the first element from the "hobbies" array
    collection.update_one({"_id": 1}, {"$pop": {"hobbies": -1}})

    # Remove the last element from the "hobbies" array
    collection.update_one({"_id": 2}, {"$pop": {"hobbies": 1}})

    users = list(collection.find())
    print(users)

    client.close()

example()
```

------

# \$1position
<a name="position"></a>

Amazon DocumentDB `$position` の修飾子は、`$push`演算子が要素を挿入する配列内の場所を指定します。`$position` 修飾子がない場合、`$push`演算子は配列の末尾に要素を挿入します。

**パラメータ**
+ `field`: 更新する配列フィールド。
+ `num`: ゼロベースのインデックス作成に基づいて要素を挿入する配列内の位置。

**注**: `$position`修飾子を使用するには、`$each`修飾子とともに表示する必要があります。

## 例 (MongoDB シェル)
<a name="position-examples"></a>

次の例は、 `$position`演算子を使用してプロジェクト管理システム内の特定の位置にタスクを挿入する方法を示しています。

**サンプルドキュメントを作成する**

```
db.projects.insertOne({ "_id": 1, "name": "Website Redesign", "tasks": ["Design mockups"] })
```

**クエリ例 1 - 緊急タスクを最初に追加する**

```
db.projects.updateOne(
   { _id: 1 },
   {
     $push: {
        tasks: {
           $each: ["Security audit", "Performance review"],
           $position: 0
        }
     }
   }
)
```

**出力 1**

```
{ "_id": 1, "name": "Website Redesign", "tasks": ["Security audit", "Performance review", "Design mockups"] }
```

**クエリの例 2 - 特定の位置にタスクを追加する**

```
db.projects.insertOne({ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Deploy to store"] })

db.projects.updateOne(
   { _id: 2 },
   {
     $push: {
        tasks: {
           $each: ["Code review", "Testing phase"],
           $position: 2
        }
     }
   }
)
```

**出力 2**

```
{ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Code review", "Testing phase", "Deploy to store"] }
```

## コードの例
<a name="position-code"></a>

`$position` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function insertTasksAtPosition() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('projects');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        tasks: {
          $each: ["Security audit", "Performance review"],
          $position: 0
        }
      }
    }
  );

  const updatedProject = await collection.findOne({ _id: 1 });
  console.log(updatedProject);

  await client.close();
}

insertTasksAtPosition();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def insert_tasks_at_position():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['projects']

    result = collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'tasks': {
                    '$each': ['Security audit', 'Performance review'],
                    '$position': 0
                }
            }
        }
    )

    updated_project = collection.find_one({'_id': 1})
    print(updated_project)

    client.close()

insert_tasks_at_position()
```

------

# \$1pull
<a name="pull"></a>

`$pull` 演算子は、指定された条件に一致する値または値のすべてのインスタンスを配列から削除するために使用されます。この演算子は、ドキュメント内の配列フィールドから特定の要素を削除する必要がある場合に便利です。

**パラメータ**
+ `field`: 値を削除する配列フィールドの名前 (複数可）。
+ `value`: 配列から削除する要素 (複数可) を決定する値または条件。

## 例 (MongoDB シェル)
<a name="pull-examples"></a>

次の例は、 `$pull`演算子を使用して配列フィールドから要素を削除する方法を示しています。

**サンプルドキュメントを作成する**

```
db.restaurants.insertMany([
  {
    name: "Pizza Hut",
    cuisine: "Italian",
    features: ["Delivery", "Takeout", "Dine-in"]
  },
  {
    name: "Sushi Saito",
    cuisine: "Japanese",
    features: ["Dine-in", "Private Dining"]
  },
  {
    name: "Taco Bell",
    cuisine: "Mexican",
    features: ["Delivery", "Takeout", "Drive-thru"]
  }
])
```

**クエリの例**

```
db.restaurants.updateMany(
  { cuisine: "Italian" },
  { $pull: { features: "Takeout" } }
)
```

**出力**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

上記のクエリは、 `cuisine`フィールドが「イタリア語」であるすべてのドキュメントから「テイクアウト」機能を削除します。

## コードの例
<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`演算子は、指定された値のすべてのインスタンスを配列フィールドから削除するために使用されます。これは、1 回のオペレーションで配列から複数の要素を削除する必要がある場合に特に便利です。

**パラメータ**
+ `field`: 要素を削除する配列フィールドの名前。
+ `value`: 配列フィールドから削除する値の配列。

## 例 (MongoDB シェル)
<a name="pullAll-examples"></a>

次の例は、 `$pullAll`演算子を使用して配列フィールドから複数の要素を削除する方法を示しています。

**サンプルドキュメントを作成する**

```
db.restaurants.insert([
  {
    "name": "Taj Mahal",
    "cuisine": "Indian",
    "features": ["Private Dining", "Live Music"]
  },
  {
    "name": "Golden Palace",
    "cuisine": "Chinese",
    "features": ["Private Dining", "Takeout"]
  },
  {
    "name": "Olive Garden",
    "cuisine": "Italian",
    "features": ["Private Dining", "Outdoor Seating"]
  }
])
```

**クエリの例**

```
db.restaurants.update(
  { "name": "Taj Mahal" },
  { $pullAll: { "features": ["Private Dining", "Live Music"] } }
)
```

**出力**

```
{
  "name": "Taj Mahal",
  "cuisine": "Indian",
  "features": []
}
```

## コードの例
<a name="pullAll-code"></a>

`$pullAll` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('restaurants');

  await collection.updateMany(
    { "name": "Taj Mahal" },
    { $pullAll: { "features": ["Private Dining", "Live Music"] } }
  );

  const updatedDocument = await collection.findOne({ "name": "Taj Mahal" });
  console.log(updatedDocument);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['restaurants']

    collection.update_many(
        {"name": "Taj Mahal"},
        {"$pullAll": {"features": ["Private Dining", "Live Music"]}}
    )

    updated_document = collection.find_one({"name": "Taj Mahal"})
    print(updated_document)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1push
<a name="push"></a>

Amazon DocumentDB の `$push`演算子は、ドキュメントの配列フィールドに項目を追加するために使用されます。この演算子は、配列全体を上書きせずに既存の配列に新しいデータを追加する必要がある場合に特に便利です。

**パラメータ**
+ `field`: 新しい要素を追加する配列フィールドの名前。
+ `value`: 配列に追加する値。
+ `position`: (オプション) 新しい要素を追加する配列内の位置を指定する修飾子。サポートされている修飾子には、 `$` (配列の末尾に を追加) と `$[]` (配列の末尾に を追加し、配列フィルターを無視) が含まれます。

## 例 (MongoDB シェル)
<a name="push-examples"></a>

次の例は、 `$push`演算子を使用してドキュメントの配列フィールドに新しい要素を追加する方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insert([
  { _id: 1, name: "John Doe", hobbies: ["reading", "swimming"] },
  { _id: 2, name: "Jane Smith", hobbies: ["gardening", "cooking"] }
])
```

**クエリの例**

```
db.users.updateOne(
  { _id: 1 },
  { $push: { hobbies: "hiking" } }
)
```

**出力**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

更新を実行すると、 を持つドキュメントの`hobbies`配列`_id: 1`が に更新されます`[&quot;reading&quot;, &quot;swimming&quot;, &quot;hiking&quot;]`。

## コードの例
<a name="push-code"></a>

`$push` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.updateOne(
    { _id: 1 },
    { $push: { hobbies: "hiking" } }
  );

  console.log(result);
  client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    result = collection.update_one(
        {'_id': 1},
        {'$push': {'hobbies': 'hiking'}}
    )

    print(result.raw_result)
    client.close()

update_document()
```

------

# \$1rename
<a name="rename"></a>

Amazon DocumentDB の `$rename`演算子は、ドキュメント内のフィールドの名前を変更するために使用されます。この演算子は、ドキュメントの構造を更新したり、新しいデータモデルに合わせる必要がある場合に特に役立ちます。

**パラメータ**
+ `field`: 名前を変更するフィールド。
+ `newName`: フィールドの新しい名前。

## 例 (MongoDB シェル)
<a name="rename-examples"></a>

次の例は、 `$rename`演算子を使用して、 `&quot;Date.DoW&quot;` フィールドを に設定してドキュメント`&quot;Date.DayOfWeek&quot;`内の `&quot;DocName&quot;`フィールドの名前を に変更する方法を示しています`&quot;Document 1&quot;`。

**サンプルドキュメントを作成する**

```
db.example.insertOne({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**クエリの例**

```
db.example.update(
    { "DocName": "Document 1" },
    { $rename: { "Date.DoW": "Date.DayOfWeek" } }
)
```

**出力**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DayOfWeek": "Saturday"
    },
    "Words": 2482
}
```

## コードの例
<a name="rename-code"></a>

`$rename` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
    const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
    const db = client.db('test');
    const collection = db.collection('example');

    await collection.updateOne(
        { "DocName": "Document 1" },
        { $rename: { "Date.DoW": "Date.DayOfWeek" } }
    );

    const updatedDoc = await collection.findOne({ "DocName": "Document 1" });
    console.log(updatedDoc);

    await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    collection.update_one(
        {"DocName": "Document 1"},
        {"$rename": {"Date.DoW": "Date.DayOfWeek"}}
    )

    updated_doc = collection.find_one({"DocName": "Document 1"})
    print(updated_doc)

    client.close()

example()
```

------

# \$1set
<a name="set-update"></a>

Amazon DocumentDB の `$set`演算子は、ドキュメント内の指定されたフィールドの値を更新するために使用されます。この演算子を使用すると、新しいフィールドを追加したり、ドキュメント内の既存のフィールドを変更したりできます。これは、Amazon DocumentDB と互換性のある MongoDB Java ドライバーの基本的な更新演算子です。

**パラメータ**
+ `field`: 更新するフィールド。
+ `value`: フィールドの新しい値。

## 例 (MongoDB シェル)
<a name="set-examples"></a>

次の例は、 `$set`演算子を使用してドキュメントの `Item`フィールドを更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.example.insert([
  {
    "Item": "Pen",
    "Colors": ["Red", "Green", "Blue", "Black"],
    "Inventory": {
      "OnHand": 244,
      "MinOnHand": 72
    }
  },
  {
    "Item": "Poster Paint",
    "Colors": ["Red", "Green", "Blue", "White"],
    "Inventory": {
      "OnHand": 120,
      "MinOnHand": 36
    }
  }
])
```

**クエリの例**

```
db.example.update(
  { "Item": "Pen" },
  { $set: { "Item": "Gel Pen" } }
)
```

**出力**

```
{
  "Item": "Gel Pen",
  "Colors": ["Red", "Green", "Blue", "Black"],
  "Inventory": {
    "OnHand": 244,
    "MinOnHand": 72
  }
}
```

## コードの例
<a name="set-code"></a>

`$set` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  await collection.updateOne(
    { "Item": "Pen" },
    { $set: { "Item": "Gel Pen" } }
  );

  const updatedDocument = await collection.findOne({ "Item": "Gel Pen" });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.example

    collection.update_one(
        {"Item": "Pen"},
        {"$set": {"Item": "Gel Pen"}}
    )

    updated_document = collection.find_one({"Item": "Gel Pen"})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1setOnInsert
<a name="setOnInsert"></a>

Amazon DocumentDB の `$setOnInsert`演算子は、ドキュメントが挿入されている場合はフィールドの値を設定するために使用されますが、ドキュメントが更新されている場合は効果がありません。

**パラメータ**
+ `field`: 設定するフィールド。
+ `value`: フィールドに割り当てる値。

## 例 (MongoDB シェル)
<a name="setOnInsert-examples"></a>

次の例は、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 - 新しいドキュメントを挿入する (アップサート)**

```
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 シェル)
<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` 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>

`$sort` 更新修飾子は、 `$push`演算子で使用すると配列要素を順序付けします。指定されたフィールド値または要素自体に基づいて、配列要素を昇順または降順に配置します。

**パラメータ**
+ `field`: 変更する配列フィールド。
+ `order`: 昇順`-1`または降順`1`に使用します。

## 例 (MongoDB シェル)
<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 シェル)
<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`演算子を使用して、「ドキュメント 1」と`DocName`等しい `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()
```

------