

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# APIsMongoDB, operasi, dan tipe data yang didukung di Amazon DocumentDB
<a name="mongo-apis"></a>

Amazon DocumentDB (dengan kompatibilitas MongoDB) adalah layanan basis data dokumen yang cepat, dapat diskalakan, sangat tersedia, dan terkelola penuh yang mendukung beban kerja MongoDB. Amazon DocumentDB kompatibel dengan MongoDB 3.6, 4.0, 5.0, dan 8.0. APIs Bagian ini mencantumkan fungsionalitas yang didukung. Untuk dukungan menggunakan APIs MongoDB dan driver, silakan berkonsultasi dengan Forum Komunitas MongoDB. Untuk dukungan menggunakan layanan Amazon DocumentDB, silakan hubungi tim dukungan yang AWS sesuai. Untuk perbedaan fungsional antara Amazon DocumentDB dan MongoDB, silakan lihat [Perbedaan fungsional: Amazon DocumentDB dan MongoDB](functional-differences.md). 

Perintah dan operator MongoDB yang hanya berlaku untuk internal atau tidak berlaku untuk layanan terkelola penuh tidak didukung dan tidak termasuk dalam daftar fungsi yang didukung.

Kami telah menambahkan lebih dari 50\$1 kemampuan tambahan sejak diluncurkan, dan akan terus bekerja mundur dari pelanggan kami untuk memberikan kemampuan yang mereka butuhkan. Untuk informasi tentang peluncuran terbaru, lihat [Pengumuman Amazon DocumentDB](https://aws.amazon.com/documentdb/resources/).

Jika ada fitur yang tidak didukung yang Anda ingin kami bangun, beri tahu kami dengan mengirimkan email dengan accountID Anda, fitur yang diminta, dan kasus penggunaan ke [tim layanan Amazon DocumentDB](mailto:documentdb-feature-request@amazon.com).
+ [Perintah basis data](#mongo-apis-database)
+ [Operator kueri dan proyeksi](#mongo-apis-query)
+ [Perbarui operator](#mongo-apis-update)
+ [Geospasial](#mongo-apis-geospatial)
+ [Metode kursor](#mongo-apis-cursor)
+ [Operator pipa agregasi](#mongo-apis-aggregation-pipeline)
+ [Jenis Data](#mongo-apis-data-types)
+ [Indeks](#mongo-apis-indexes)

## Perintah basis data
<a name="mongo-apis-database"></a>

**Topics**
+ [Perintah administratif](#mongo-apis-dababase-administrative)
+ [Agregasi](#mongo-apis-dababase-aggregation)
+ [Autentikasi](#mongo-apis-dababase-authentication)
+ [Perintah diagnostik](#mongo-apis-dababase-diagnostics)
+ [Operasi kueri dan tulis](#mongo-apis-dababase-query-write)
+ [Perintah manajemen peran](#mongo-apis-database-role-management)
+ [Perintah sesi](#mongo-apis-dababase-sessions)
+ [Manajemen pengguna](#mongo-apis-dababase-user-management)
+ [Perintah sharding](#mongo-apis-dababase-sharding)

### Perintah administratif
<a name="mongo-apis-dababase-administrative"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  Koleksi Terbatas  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  cloneCollectionAsTertutup  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  collMod  |  Sebagian  |  Sebagian  |  Sebagian  |  Sebagian  |  Sebagian  | 
|  CollMod: expireAfterSeconds  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  convertToCapped  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  copydb  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  Buat  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  createView  |  Tidak  |  Tidak  |  Tidak  |  Ya  |  Tidak  | 
|  createIndex  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  currentOp  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  drop  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  dropDatabase  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  dropIndexes  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  filemd5  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  getAuditConfig  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  killCursors  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  killOp  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  ListCollection\$1  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  listDatabases  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  listIndexes  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  reIndex  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Tidak  | 
|  renameCollection  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  setAuditConfig  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 

\$1 `type` Kunci dalam opsi filter tidak didukung.

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  agregasi  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  hitungan  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  berbeda  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  mapReduce  |  Tidak  |  Tidak  |  Tidak  |  Ya  |  Tidak  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  diautentikasi  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  logout  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Perintah diagnostik
<a name="mongo-apis-dababase-diagnostics"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  buildInfo  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  collStats  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  connPoolStats  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  connectionStatus  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  dataSize  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  dbHash  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  dbStats  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  jelaskan  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  jelaskan: executionStats  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  fitur  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  hostInfo  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  listCommands  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  profiler  |  [Ya](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [Ya](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [Ya](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [Ya](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  Tidak  | 
|  serverStatus  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  atas  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operasi kueri dan tulis
<a name="mongo-apis-dababase-query-write"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  Mengelola aliran  |  [Ya](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [Ya](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [Ya](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [Ya](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  Tidak  | 
|  hapus  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  cari  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  findAndModify  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  getLastError  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  getMore  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  getPrevError  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  GridFS  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  sisipkan  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  parallelCollectionScan  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  resetError  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  perbarui  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  ReplaceOne  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Perintah manajemen peran
<a name="mongo-apis-database-role-management"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  createRole  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  dropAllRolesFromDatabase  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  dropRole  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  grantRolesToPeran  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  revokeRolesFromPeran  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  revokePrivilegesFromPeran  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  rolesInfo  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  updateRole  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 

### Perintah sesi
<a name="mongo-apis-dababase-sessions"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  abortTransaction  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  commitTransaction  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  endSessions  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|   killAllSessions  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  killAllSessionsByPattern  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  killSessions  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  refreshsessions  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  startSession  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  createUser  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  dropAllUsersFromDatabase  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  dropUser  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  grantRolesToPengguna  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  revokeRolesFromPengguna  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  updateUser  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  UsersInfo  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | Cluster elastis | 
| --- | --- | 
|  abortReshardCollection  |  Tidak  | 
|  AddsHard  |  Tidak  | 
|  addShardToZona  |  Tidak  | 
|  balancerCollectionStatus  |  Tidak  | 
|  BalancerStart  |  Tidak  | 
|  BalancerStatus  |  Tidak  | 
|  BalancerSTOP  |  Tidak  | 
|  checkShardingIndex  |  Tidak  | 
|  clearJumboFlag  |  Tidak  | 
|  cleanupOrphaned  |  Tidak  | 
|  cleanupReshardCollection  |  Tidak  | 
|  commitReshardCollection  |  Tidak  | 
|  Aktifkan Sharding  |  Ya  | 
|  flushRouterConfig  |  Tidak  | 
|  getShardMap  |  Tidak  | 
|  getShardVersion  |  Tidak  | 
|  ISDBgrid  |  Tidak  | 
|  ListShards  |  Tidak  | 
|  MedianKey  |  Tidak  | 
|  MoveChunk  |  Tidak  | 
|  MovePrimary  |  Tidak  | 
|  MergeChunks  |  Tidak  | 
|  refineCollectionShardKunci  |  Tidak  | 
|  MenghapusHard  |  Tidak  | 
|  removeShardFromZona  |  Tidak  | 
|  ResHardCollection  |  Tidak  | 
|  setAllowMigrations  |  Tidak  | 
|  setShardVersion  |  Tidak  | 
|  ShardCollection  |  Ya  | 
|  ShardingState  |  Tidak  | 
|  terbelah  |  Tidak  | 
|  SplitVector  |  Tidak  | 
|  UnsetSharding  |  Tidak  | 
|  updateZoneKeyRentang  |  Tidak  | 

## Operator kueri dan proyeksi
<a name="mongo-apis-query"></a>

**Topics**
+ [Operator Array](#mongo-apis-query-array-operators)
+ [Operator Bitwise](#mongo-apis-query-bitwise-operators)
+ [Operator komentar](#mongo-apis-query-comment-operator)
+ [Operator perbandingan](#mongo-apis-query-comparison-operators)
+ [Operator elemen](#mongo-apis-query-element-operators)
+ [Operator kueri evaluasi](#mongo-apis-query-evaluation-operators)
+ [Operator logis](#mongo-apis-query-logical-operators)
+ [Operator proyeksi](#mongo-apis-projection-operators)

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1 semua](all.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1elemMatch](elemMatch.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1size](size-query.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1bitsAllSet](bitsAllSet.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1bitsAnySet](bitsAnySet.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1bitsAllClear](bitsAllClear.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1bitsAnyClear](bitsAnyClear.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1comment](comment.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1eq](eq.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1gt](gt.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1gte](gte.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1in](in.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1lt](lt.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1lte](lte.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1ne](ne.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1nin](nin.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1exists](exists.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1type](type.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator kueri evaluasi
<a name="mongo-apis-query-evaluation-operators"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1expr](expr.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  [\$1jsonSchema](jsonSchema.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  [\$1mod](mod-query.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1regex](regex.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1text](text.md)  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Tidak  | 
|  \$1where  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1and](and.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1nor](nor.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1not](not.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1or](or.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1](dollar-projection.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1elemMatch](elemMatch.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1meta](meta.md)  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Tidak  | 
|  [\$1slice](slice-projection.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

## Perbarui operator
<a name="mongo-apis-update"></a>

**Topics**
+ [Operator array](#mongo-apis-update-array)
+ [Operator Bitwise](#mongo-apis-update-bitwise)
+ [Operator lapangan](#mongo-apis-update-field)
+ [Perbarui pengubah](#mongo-apis-update-modifiers)

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1](dollar-update.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1[]](dollarBrackets-update.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1[<identifier>]](dollarIdentifier-update.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1addToSet](addToSet.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 pop](pop.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 PullAll](pullAll.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 tarik](pull.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 dorong](push.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1 bit](bit.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator lapangan
<a name="mongo-apis-update-field"></a>


| Operator | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1CurrentDate](currentDate.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 inc](inc.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1max](max-update.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1min](min-update.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 mul](mul.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 ganti nama](rename.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1set](set-update.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1setOnInsert](setOnInsert.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1unset](unset-update.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Operator | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1 masing-masing](each.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 posisi](position.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1slice](slice-update.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1sort](sort-update.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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

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


| Pemilih Kueri | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  \$1box  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1center  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1centerSphere  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1geometry](geometry.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1maxDistance](maxDistance.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1minDistance](minDistance.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1nearSphere](nearSphere.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1polygon  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1uniqueDocs  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1geointersects](geoIntersects.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1geowithin](geoWithin.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1near](near.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1nearSphere](nearSphere.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1polygon  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1uniqueDocs  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 

## Metode kursor
<a name="mongo-apis-cursor"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  cursor.batchsize ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  cursor.close ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  cursor.collation()  |  Tidak  |  Tidak  |  Tidak  |  Ya  |  Tidak  | 
|  cursor.comment ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  cursor.count ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  cursor.explain ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.foreach ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  cursor.hasNext ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  cursor.hint ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya\$1  | 
|  cursor.isClosed ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  cursor.isExhausted ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.itcount ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.limit ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.map ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.max ()  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  cursor.maxScan ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.maxTimes ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.min ()  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  cursor.next ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  kursor. noCursorTimeout()  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  kursor. objsLeftInBatch ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.pretty ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.readconcern ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.readPref ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.returnKey ()  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  kursor. showRecordId()  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  cursor.size ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.skip ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.sort ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  cursor.tailable ()  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  cursor.toArray ()  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 

\$1 Indeks `hint` didukung dengan ekspresi indeks. Misalnya, `db.foo.find().hint({x:1})`.

## Operator pipa agregasi
<a name="mongo-apis-aggregation-pipeline"></a>

**Topics**
+ [Ekspresi akumulator](#mongo-apis-aggregation-pipeline-accumulator-expressions)
+ [Operator aritmatika](#mongo-apis-aggregation-pipeline-arithmetic)
+ [Operator array](#mongo-apis-aggregation-pipeline-array)
+ [Operator Boolean](#mongo-apis-aggregation-pipeline-boolean)
+ [Operator perbandingan](#mongo-apis-aggregation-pipeline-comparison)
+ [Operator ekspresi bersyarat](#mongo-apis-aggregation-pipeline-conditional)
+ [Operator tipe data](#mongo-apis-aggregation-pipeline-data-type)
+ [Operator ukuran data](#mongo-apis-aggregation-pipeline-data-size)
+ [Operator tanggal](#mongo-apis-aggregation-pipeline-date)
+ [Operator literal](#mongo-apis-aggregation-pipeline-literal)
+ [Gabungkan operator](#mongo-apis-aggregation-pipeline-merge)
+ [Operator alami](#mongo-apis-aggregation-pipeline-natural)
+ [Tetapkan operator](#mongo-apis-aggregation-pipeline-set)
+ [Operator panggung](#mongo-apis-aggregation-pipeline-stage)
+ [Operator String](#mongo-apis-aggregation-pipeline-string)
+ [Variabel sistem](#mongo-apis-aggregation-pipeline-system-variables)
+ [Operator pencarian teks](#mongo-apis-aggregation-pipeline-text-search)
+ [Jenis operator konversi](#mongo-apis-aggregation-pipeline-type)
+ [Operator variabel](#mongo-apis-aggregation-pipeline-variable)
+ [Operator lain-lain](#mongo-apis-aggregation-pipeline-misc)

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


| Ekspresi | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  \$1 akumulator  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1addToSet](addToSet-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1avg](avg.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1count](count.md)  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1 KovariancePOP  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1 kovarianceSamp  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1 DenseRank  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1 turunan  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1DocumentNumber  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1expMovingAvg  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1first](first.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1 integral  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1last](last.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1max](max.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1min](min.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1push](push-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1 peringkat  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1 shift  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1stdDevPop  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1stdDevSamp  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1sum](sum.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator aritmatika
<a name="mongo-apis-aggregation-pipeline-arithmetic"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1abs](abs.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1add](add.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1ceil](ceil.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1divide](divide.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1exp](exp.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1floor](floor.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1In](ln.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1log](log.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1log10](log10.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1mod](mod.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1multiply](multiply.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1pow](pow.md)  |  Tidak  |  Tidak  |  Tidak  |  Ya  |  Tidak  | 
|  \$1 bulat  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1sqrt](sqrt.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1subtract](subtract.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1trunc  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1arrayElemAt](arrayElemAt.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1arrayToObject](arrayToObject.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1concatArrays](concatArrays.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1filter](filter.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1first](first.md)  |  -  |  -  |  Ya  |  Ya  |  Tidak  | 
|  [\$1in](in-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1indexOfArray](indexOfArray.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1isArray](isArray.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1last](last.md)  |  -  |  -  |  Ya  |  Ya  |  Tidak  | 
|  [\$1objectToArray](objectToArray.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1range](range.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1reverseArray](reverseArray.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1reduce](reduce.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1size](size.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1slice](slice.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1zip](zip.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1and](and-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1not](not-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1or](or-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator perbandingan
<a name="mongo-apis-aggregation-pipeline-comparison"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1cmp](cmp.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1eq](eq-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1gt](gt-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1gte](gte-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1lt](lt-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1lte](lte-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1ne](ne-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator ekspresi bersyarat
<a name="mongo-apis-aggregation-pipeline-conditional"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1cond](cond.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1ifNull](ifNull.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1switch](switch.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 

### Operator tipe data
<a name="mongo-apis-aggregation-pipeline-data-type"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1type](type-aggregation.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator ukuran data
<a name="mongo-apis-aggregation-pipeline-data-size"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  \$1 BinarySize  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1 BSONSize  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 

### Operator tanggal
<a name="mongo-apis-aggregation-pipeline-date"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1 DateAdd](dateAdd.md)  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Ya  | 
|  [\$1 DateDiff](dateDiff.md)  |  -  |  -  |  Ya  |  Ya  |  Tidak  | 
|  \$1dateFromParts  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1dateFromString](dateFromString.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 DateSubtract](dateSubtract.md)  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Ya  | 
|  \$1dateToParts  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1dateToString](dateToString.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 DateTrunc](dateTrunc.md)  |  -  |  -  |  Tidak  |  Ya  |  Tidak  | 
|  [\$1dayOfMonth](dayOfMonth.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1dayOfWeek](dayOfWeek.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1dayOfYear](dayOfYear.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1hour](hour.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 isoDayOf Minggu](isoDayOfWeek.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1isoWeek](isoWeek.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1isoWeekYear](isoWeekYear.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1millisecond](millisecond.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1minute](minute.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1month](month.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1second](second.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1week](week.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1year](year.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1literal](literal.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1mergeObjects](mergeObjects.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator alami
<a name="mongo-apis-aggregation-pipeline-natural"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1natural](natural.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Tetapkan operator
<a name="mongo-apis-aggregation-pipeline-set"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1allElementsTrue](allElementsTrue.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1anyElementTrue](anyElementTrue.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1setDifference](setDifference.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1setEquals](setEquals.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1setIntersection](setIntersection.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1setIsSubset](setIsSubset.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1setUnion](setUnion.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1setWindowFields  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 

### Operator panggung
<a name="mongo-apis-aggregation-pipeline-stage"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1addFields](addFields.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1bucket](bucket.md)  |  Tidak  |  Tidak  |  Tidak  |  Ya  |  Tidak  | 
|  \$1bucketAuto  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1 ChangeStream](changeStream.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  [\$1collStats](collStats.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  [\$1count](count.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1currentOp](currentOp.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1facet  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1geoNear](geoNear.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1graphLookup  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1group](group.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1indexStats](indexStats.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1limit](limit.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1listLocalSessions  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1listSessions  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1lookup](lookup.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1match](match.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 bergabung](merge.md)  |  -  |  -  |  Tidak  |  Ya  |  Tidak  | 
|  [\$1out](out.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  \$1planCacheStats  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1project](project.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1redact](redact.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1replaceRoot](replaceRoot.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1sample](sample.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1set](set-stage.md)  |  -  |  -  |  Tidak  |  Ya  |  Tidak  | 
|  \$1setWindowFields  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1skip](skip.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1sort](sort.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1sortByCount  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  \$1unionDengan  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1unset](unset-stage.md)  |  -  |  -  |  Tidak  |  Ya  |  Tidak  | 
|  [\$1unwind](unwind.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1 GantiDengan](replaceWith.md)  |  Tidak  |  Tidak  |  Tidak  |  Ya  |  Tidak  | 
|  [\$1 VectorSearch](vectorSearch.md)  |  Tidak  |  Tidak  |  Tidak  |  Ya  |  Tidak  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1concat](concat.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1indexOfBytes](indexOfBytes.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1indexOfCP](indexOfCP.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1ltrim](ltrim.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  [\$1RegexFind](regexFind.md)  |  -  |  -  |  Ya  |  Ya  |  Tidak  | 
|  [\$1regexFindAll](regexFindAll.md)  |  -  |  -  |  Ya  |  Ya  |  Tidak  | 
|  [\$1RegexMatch](regexMatch.md)  |  -  |  -  |  Ya  |  Ya  |  Tidak  | 
|  [\$1 GantiSemua](replaceAll.md)  |  -  |  -  |  Ya  |  Ya  |  Tidak  | 
|  [\$1 GantiSatu](replaceOne.md)  |  -  |  -  |  Ya  |  Ya  |  Tidak  | 
|  [\$1rtrim](rtrim.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 
|  [\$1split](split.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1strcasecmp](strcasecmp.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1strLenBytes](strLenBytes.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1strLenCP](strLenCP.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1substr](substr.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1substrBytes](substrBytes.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1substrCP](substrCP.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1toLower](toLower.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1toUpper](toUpper.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1trim](trim.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Tidak  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  \$1\$1CURRENT  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1\$1DESCEND](DESCEND.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1\$1KEEP](KEEP.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1\$1PRUNE](PRUNE.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1\$1REMOVE  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1 AKAR](ROOT.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator pencarian teks
<a name="mongo-apis-aggregation-pipeline-text-search"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1meta](meta-aggregation.md)  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Tidak  | 
|  [\$1 pencarian](search.md)  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Tidak  | 

### Jenis operator konversi
<a name="mongo-apis-aggregation-pipeline-type"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1convert](convert.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  \$1 isNumber  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1toBool](toBool.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1toDate](toDate.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1toDecimal](toDecimal.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1toDouble](toDouble.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1toInt](toInt.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1toLong](toLong.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1toObjectId](toObjectId.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1toString](toString.md)  |  Tidak  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator variabel
<a name="mongo-apis-aggregation-pipeline-variable"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1let](let.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  [\$1map](map.md)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 

### Operator lain-lain
<a name="mongo-apis-aggregation-pipeline-misc"></a>


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  \$1 GetField  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 
|  [\$1 rand](rand.md)  |  -  |  -  |  Tidak  |  Ya  |  Tidak  | 
|  \$1 Samplerate  |  -  |  -  |  Tidak  |  Tidak  |  Tidak  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  32-bit Integer (int)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  64-bit Integer (long)  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Array  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Data Biner  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Boolean  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Date  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  DBPointer  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  DBRefs  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  Decimal128  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Ganda  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  JavaScript  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  JavaScript(dengan ruang lingkup)  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  MaxKey  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  MinKey  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Null  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Objek  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  ObjectId  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Ekspresi reguler  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Tali  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Simbol  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  Stempel waktu  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Tidak terdefinisi  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 

## Indeks dan properti indeks
<a name="mongo-apis-index"></a>

**Topics**
+ [Indeks](#mongo-apis-indexes)
+ [Properti indeks](#mongo-apis-index-properties)

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  2dsphere  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Indeks 2d  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  Indeks Gabungan  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Indeks hashed  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  Indeks Multikey  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Indeks Bidang Tunggal  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Indeks Teks  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Tidak  | 
|  Wildcard  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 

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


| Perintah | 3.6 | 4.0 | 5.0 | 8.0 | Cluster elastis | 
| --- | --- | --- | --- | --- | --- | 
|  Latar Belakang  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Tidak peka huruf besar/kecil  |  Tidak  |  Tidak  |  Tidak  |  Ya  |  Tidak  | 
|  Tersembunyi  |  Tidak  |  Tidak  |  Tidak  |  Tidak  |  Tidak  | 
|  Sebagian  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Tidak  | 
|  Jarang  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Teks  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Tidak  | 
|  TTL  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  Unik  |  Ya  |  Ya  |  Ya  |  Ya  |  Ya  | 
|  vektor  |  Tidak  |  Tidak  |  Ya  |  Ya  |  Tidak  | 

Untuk informasi rinci tentang operator MongoDB tertentu, lihat topik berikut:
+ [Operator pipa agregasi](mongo-apis-aggregation-pipeline-operators.md)
+ [Geospasial](mongo-apis-geospatial-operators.md)
+ [Operator proyeksi](#mongo-apis-projection-operators)
+ [Perbarui operator](mongo-apis-update-operators.md)

# Operator pipa agregasi
<a name="mongo-apis-aggregation-pipeline-operators"></a>

Bagian ini memberikan informasi terperinci tentang operator pipeline agregasi yang didukung oleh Amazon DocumentDB.

**Topics**
+ [\$1\$1DESCEND](DESCEND.md)
+ [\$1\$1KEEP](KEEP.md)
+ [\$1\$1PRUNE](PRUNE.md)
+ [\$1 AKAR](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)
+ [\$1 ChangeStream](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)
+ [\$1 DateAdd](dateAdd.md)
+ [\$1 DateDiff](dateDiff.md)
+ [\$1dateFromString](dateFromString.md)
+ [\$1 DateSubtract](dateSubtract.md)
+ [\$1dateToString](dateToString.md)
+ [\$1 DateTrunc](dateTrunc.md)
+ [\$1dayOfMonth](dayOfMonth.md)
+ [\$1dayOfWeek](dayOfWeek.md)
+ [\$1dayOfYear](dayOfYear.md)
+ [\$1divide](divide.md)
+ [\$1eq](eq-aggregation.md)
+ [\$1exp](exp.md)
+ [\$1filter](filter.md)
+ [\$1first](first.md)
+ [\$1floor](floor.md)
+ [\$1geoNear](geoNear.md)
+ [\$1group](group.md)
+ [\$1gt](gt-aggregation.md)
+ [\$1gte](gte-aggregation.md)
+ [\$1hour](hour.md)
+ [\$1ifNull](ifNull.md)
+ [\$1in](in-aggregation.md)
+ [\$1indexOfArray](indexOfArray.md)
+ [\$1indexOfBytes](indexOfBytes.md)
+ [\$1indexOfCP](indexOfCP.md)
+ [\$1indexStats](indexStats.md)
+ [\$1isArray](isArray.md)
+ [\$1 isoDayOf Minggu](isoDayOfWeek.md)
+ [\$1isoWeek](isoWeek.md)
+ [\$1isoWeekYear](isoWeekYear.md)
+ [\$1last](last.md)
+ [\$1let](let.md)
+ [\$1limit](limit.md)
+ [\$1literal](literal.md)
+ [\$1In](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)
+ [\$1 bergabung](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)
+ [\$1 rand](rand.md)
+ [\$1range](range.md)
+ [\$1redact](redact.md)
+ [\$1reduce](reduce.md)
+ [\$1RegexFind](regexFind.md)
+ [\$1regexFindAll](regexFindAll.md)
+ [\$1RegexMatch](regexMatch.md)
+ [\$1 GantiSemua](replaceAll.md)
+ [\$1 GantiSatu](replaceOne.md)
+ [\$1replaceRoot](replaceRoot.md)
+ [\$1 GantiDengan](replaceWith.md)
+ [\$1reverseArray](reverseArray.md)
+ [\$1rtrim](rtrim.md)
+ [\$1sample](sample.md)
+ [\$1 pencarian](search.md)
+ [\$1second](second.md)
+ [\$1set](set-stage.md)
+ [\$1setDifference](setDifference.md)
+ [\$1setEquals](setEquals.md)
+ [\$1setIntersection](setIntersection.md)
+ [\$1setIsSubset](setIsSubset.md)
+ [\$1setUnion](setUnion.md)
+ [\$1skip](skip.md)
+ [\$1slice](slice.md)
+ [\$1size](size.md)
+ [\$1sort](sort.md)
+ [\$1split](split.md)
+ [\$1sqrt](sqrt.md)
+ [\$1strLenBytes](strLenBytes.md)
+ [\$1strLenCP](strLenCP.md)
+ [\$1strcasecmp](strcasecmp.md)
+ [\$1substr](substr.md)
+ [\$1substrBytes](substrBytes.md)
+ [\$1substrCP](substrCP.md)
+ [\$1subtract](subtract.md)
+ [\$1sum](sum.md)
+ [\$1switch](switch.md)
+ [\$1toBool](toBool.md)
+ [\$1toDate](toDate.md)
+ [\$1toDecimal](toDecimal.md)
+ [\$1toDouble](toDouble.md)
+ [\$1toInt](toInt.md)
+ [\$1toLong](toLong.md)
+ [\$1toLower](toLower.md)
+ [\$1toObjectId](toObjectId.md)
+ [\$1toString](toString.md)
+ [\$1toUpper](toUpper.md)
+ [\$1trim](trim.md)
+ [\$1type](type-aggregation.md)
+ [\$1unset](unset-stage.md)
+ [\$1unwind](unwind.md)
+ [\$1 VectorSearch](vectorSearch.md)
+ [\$1week](week.md)
+ [\$1year](year.md)
+ [\$1zip](zip.md)

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

`$$DESCEND`Operator di Amazon DocumentDB adalah operator array posisi khusus yang digunakan dalam tahap pipeline. `$redact` Ini menginstruksikan pipa agregasi untuk turun ke dokumen saat ini dan memproses semua bidang, terlepas dari tingkat sarangnya.

Ketika `$redact` tahap bertemu dengan `$$DESCEND` operator, itu akan membuat semua bidang dalam dokumen saat ini terlihat dan memprosesnya lebih jauh ke bawah pipa. Ini berguna ketika Anda ingin menyunting atau memangkas bidang tertentu secara selektif berdasarkan suatu kondisi, sambil mempertahankan struktur dokumen.

**Parameter**

Tidak ada.

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

Dalam contoh ini, kita akan menggunakan `$redact` panggung dengan `$$DESCEND` operator untuk secara selektif menampilkan dokumen di mana `code` bidang sama dengan “Reg”.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="DESCEND-code"></a>

Untuk melihat contoh kode untuk menggunakan `$$DESCEND` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Variabel `$$KEEP` sistem digunakan dengan `$redact` tahapan dalam pipa agregasi untuk menjaga dokumen atau bidang saat ini tidak berubah dan memasukkannya ke dalam output.

**Parameter**

Tidak ada

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

Contoh berikut menunjukkan penggunaan `$$KEEP` dalam pipeline agregasi Amazon DocumentDB. Dokumen hanya disimpan jika akses sama dengan “publik”, jika tidak maka akan dihapus.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="KEEP-code"></a>

Untuk melihat contoh kode untuk menggunakan `$$KEEP` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Variabel `$$PRUNE` sistem digunakan dengan `$redact` tahapan dalam pipa agregasi untuk mengecualikan dokumen atau level dokumen tertanam dari hasil. Ketika suatu kondisi dievaluasi`$$PRUNE`, dokumen atau subdokumen saat ini dihapus dari output. Ini biasanya digunakan dengan `$$DESCEND` (untuk menyimpan dan melintasi dokumen) atau `$$KEEP` (untuk menyimpan dokumen di semua tingkatan).

**Parameter**

Tidak ada. Variabel `$$PRUNE` sistem digunakan tanpa parameter apa pun dan harus digunakan dengan`$redact`.

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

Contoh berikut menunjukkan cara menggunakan `$$PRUNE` dengan `$redact` untuk mengecualikan pengguna berusia di atas 30 tahun dari hasil.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="PRUNE-code"></a>

Untuk melihat contoh kode untuk menggunakan `$$PRUNE` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------

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

`$ROOT`Operator di Amazon DocumentDB digunakan untuk mereferensikan seluruh dokumen input dalam pipeline agregasi. Ini memungkinkan Anda untuk mengakses dan memanipulasi dokumen lengkap, termasuk semua bidang dan struktur bersarangnya.

**Parameter**

Tidak ada

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

Contoh ini menunjukkan penggunaan `$ROOT` untuk membuat log audit yang menangkap dokumen asli lengkap bersama dengan metadata tentang kapan diproses.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="ROOT-code"></a>

Untuk melihat contoh kode untuk menggunakan `$ROOT` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$abs`Operator di Amazon DocumentDB mengembalikan nilai absolut dari suatu angka. Ini dapat digunakan dalam pipa agregasi untuk melakukan operasi matematika pada bidang numerik.

**Parameter**
+ `number`: Ekspresi numerik yang nilai absolutnya akan dikembalikan.

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

Contoh ini menunjukkan penggunaan `$abs` operator untuk menemukan nilai absolut dari bidang numerik.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="abs-code"></a>

Untuk melihat contoh kode untuk menggunakan `$abs` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$add`Operator di Amazon DocumentDB digunakan untuk menambahkan angka atau tanggal bersama-sama. Ini dapat digunakan untuk melakukan operasi aritmatika pada bidang numerik atau untuk melakukan aritmatika tanggal dengan menambahkan sejumlah unit waktu ke bidang tanggal.

**Parameter**
+ `expression1`: Nomor atau tanggal pertama untuk ditambahkan.
+ `expression2`: Angka atau tanggal kedua untuk ditambahkan.
+ `expression3`: (opsional) Nomor atau tanggal tambahan untuk ditambahkan.

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

Contoh berikut menunjukkan bagaimana menggunakan `$add` operator untuk menambahkan dua angka bersama-sama.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

Dalam contoh ini, `$add` operator digunakan untuk menambahkan nilai `a` dan `b` bidang untuk setiap dokumen dan menyimpan hasilnya di `sum` bidang.

## Contoh kode
<a name="add-code"></a>

Untuk melihat contoh kode untuk menggunakan `$add` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$addToSet` agregasi mengembalikan array nilai unik dari ekspresi tertentu untuk setiap grup. Ini digunakan dalam `$group` tahap untuk mengakumulasi nilai yang berbeda, secara otomatis menghilangkan duplikat.

**Parameter**
+ `expression`: Ekspresi untuk mengevaluasi setiap dokumen dalam grup.

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

Contoh berikut menunjukkan penggunaan `$addToSet` operator untuk mengumpulkan kota-kota unik di mana pesanan ditempatkan untuk setiap pelanggan.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="addToSet-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$addToSet` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$addFields`Tahap dalam pipeline agregasi Amazon DocumentDB memungkinkan Anda menambahkan bidang terkomputasi baru ke dokumen. Ini dapat berguna untuk menambahkan data yang diturunkan atau diubah ke dokumen.

**Parameter**
+ `newField`: Nama bidang baru untuk ditambahkan.
+ `expression`: Ekspresi yang menyelesaikan nilai bidang baru.

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

Contoh berikut menunjukkan bagaimana menggunakan `$addFields` untuk menambahkan bidang baru `TotalInventory` yang menghitung total inventaris berdasarkan `Inventory.OnHand` dan `Inventory.OrderQnty` bidang.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="addFields-code"></a>

Untuk melihat contoh kode untuk menggunakan `$addFields` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Baru dari versi 4.0

`$allElementsTrue`Operator digunakan untuk memeriksa apakah semua elemen dalam array mengevaluasi ke nilai sebenarnya.

**Parameter**
+ `expression`: Ekspresi yang mengevaluasi array.

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

Contoh berikut menunjukkan penggunaan `$allElementsTrue` untuk memeriksa apakah semua elemen dalam array benar.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

Dalam contoh ini, query memeriksa apakah semua elemen dalam `scores` array lebih besar dari 0. Dokumen dengan `&quot;name&quot;: &quot;Jane&quot;` dikecualikan karena `scores` array berisi 0, yang merupakan nilai palsu.

## Contoh kode
<a name="allElementsTrue-code"></a>

Untuk melihat contoh kode untuk menggunakan `$allElementsTrue` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$and` agregasi mengevaluasi beberapa ekspresi dan mengembalikan `true` hanya jika semua ekspresi mengevaluasi. `true` Jika ada ekspresi`false`, ia kembali`false`.

**Parameter**
+ `expressions`: Sebuah array ekspresi untuk mengevaluasi.

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

Contoh berikut menunjukkan penggunaan `$and` operator untuk memeriksa apakah produk memenuhi beberapa kriteria.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="and-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$and` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0

`$anyElementTrue`Operator digunakan untuk menentukan apakah ada elemen dalam array yang benar.

**Parameter**
+ `field`: Bidang array untuk mengevaluasi.

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

Contoh berikut menunjukkan penggunaan `$anyElementTrue` untuk memeriksa apakah ada elemen dalam array benar.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="anyElementTrue-code"></a>

Untuk melihat contoh kode untuk menggunakan `$anyElementTrue` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$arrayElemAt`Operator di Amazon DocumentDB memungkinkan Anda untuk mengambil elemen dari array dengan posisi indeksnya. Ini sangat berguna ketika Anda perlu mengakses elemen tertentu dalam bidang array dalam dokumen Anda.

**Parameter**
+ `array`: Array input dari mana elemen akan diambil.
+ `index`: Posisi indeks berbasis nol dari elemen untuk mengambil. Nilai ini harus berupa bilangan bulat non-negatif.

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

Dalam contoh ini, kita akan menunjukkan bagaimana menggunakan `$arrayElemAt` operator untuk mengambil elemen tertentu dari `flight_miles` array dalam `miles` koleksi.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

Dalam contoh ini, kita menggunakan `$arrayElemAt` operator untuk mengambil elemen pertama dan terakhir dari `flight_miles` array untuk setiap dokumen.

## Contoh kode
<a name="arrayElemAt-code"></a>

Untuk melihat contoh kode untuk menggunakan `$arrayElemAt` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$arrayToObject`Operator di Amazon DocumentDB adalah kebalikan dari operator. `$objectToArray` Dibutuhkan array dokumen pasangan kunci-nilai dan mengubahnya menjadi satu dokumen. Ini sangat berguna ketika Anda perlu mengubah array pasangan kunci-nilai kembali ke objek atau struktur dokumen.

**Parameter**
+ `array expression`: Ekspresi yang menyelesaikan ke array. Elemen array harus dokumen dengan dua bidang: `k` (kunci) dan `v` (nilai).

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

Contoh di bawah ini menunjukkan bagaimana menggunakan `$arrayToObject` untuk mengkonversi array pasangan kunci-nilai kembali ke dokumen.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

Dalam contoh ini, `$objectToArray` operator digunakan untuk mengubah `inventory` objek menjadi array pasangan kunci-nilai. `$arrayToObject`Operator kemudian digunakan untuk mengubah array kembali menjadi dokumen, memulihkan struktur objek asli.

## Contoh kode
<a name="arrayToObject-code"></a>

Untuk melihat contoh kode untuk menggunakan `$arrayToObject` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$avg` agregasi di Amazon DocumentDB menghitung nilai rata-rata ekspresi yang ditentukan di seluruh dokumen yang dimasukkan ke panggung. Operator ini berguna untuk menghitung rata-rata bidang numerik atau ekspresi di satu set dokumen.

**Parameter**
+ `expression`: Ekspresi yang digunakan untuk menghitung rata-rata. Ini bisa berupa jalur bidang (misalnya`"$field"`) atau ekspresi (misalnya`{ $multiply: ["$field1", "$field2"] }`).

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

Contoh berikut menunjukkan bagaimana menggunakan `$avg` operator untuk menghitung skor rata-rata di satu set dokumen siswa.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="avg-code"></a>

Untuk melihat contoh kode untuk menggunakan `$avg` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Baru dari versi 8.0

Tidak didukung oleh cluster elastis.

Tahap `$bucket` agregasi di Amazon DocumentDB memungkinkan Anda mengelompokkan dokumen masukan ke dalam bucket berdasarkan ekspresi dan batas bucket yang ditentukan. Ini dapat berguna untuk menganalisis data yang termasuk dalam rentang nilai atau kategori tertentu.

**Parameter**
+ `groupBy`(required): Ekspresi yang menentukan nilai untuk dikelompokkan menurut.
+ `boundaries`(required): Array nilai ganda yang menentukan batas bucket. Dokumen ditugaskan ke ember berdasarkan nilai `groupBy` ekspresi yang termasuk dalam batas-batas yang ditentukan.
+ `default`(opsional): Nilai literal yang merupakan output untuk dokumen yang nilai `groupBy` ekspresinya tidak termasuk dalam batas yang ditentukan.
+ `output`(opsional): Objek yang menentukan informasi yang akan dikeluarkan untuk setiap bucket. Anda dapat menggunakan operator akumulator seperti`$sum`,, `$avg``$min`, dan `$max` untuk menghitung agregasi untuk setiap bucket.

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

Contoh berikut menunjukkan bagaimana menggunakan `$bucket` panggung untuk mengelompokkan data penjualan berdasarkan kisaran harga.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="bucket-code"></a>

Untuk melihat contoh kode untuk menggunakan `$bucket` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

Baru dari versi 4.0

`$ceil`Operator di Amazon DocumentDB, seperti di MongoDB, membulatkan angka ke bilangan bulat terdekat. Ini berguna ketika Anda perlu melakukan operasi matematika pada bidang numerik dan memastikan hasilnya adalah bilangan bulat.

**Parameter**
+ `expression`: Ekspresi numerik untuk dibulatkan.

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

Contoh ini menunjukkan bagaimana menggunakan `$ceil` operator untuk mengumpulkan bidang numerik.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="ceil-code"></a>

Untuk melihat contoh kode untuk menggunakan `$ceil` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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()
```

------

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

Tidak didukung oleh cluster elastis.

Tahap `$changeStream` agregasi membuka kursor aliran perubahan untuk memantau perubahan real-time ke koleksi. Ia mengembalikan perubahan dokumen peristiwa ketika menyisipkan, memperbarui, mengganti, atau menghapus operasi terjadi.

**Parameter**
+ `fullDocument`: Menentukan apakah akan mengembalikan dokumen lengkap untuk operasi update. Pilihannya adalah `default` atau`updateLookup`.
+ `resumeAfter`: Opsional. Lanjutkan token untuk melanjutkan dari titik tertentu dalam aliran perubahan.
+ `startAtOperationTime`: Opsional. Stempel waktu untuk memulai aliran perubahan dari.
+ `allChangesForCluster`: Opsional. Nilai Boolean. Kapan`true`, perhatikan semua perubahan di seluruh cluster (untuk database admin). Ketika `false` (default), hanya menonton koleksi yang ditentukan.

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

Contoh berikut menunjukkan menggunakan `$changeStream` panggung untuk memantau perubahan koleksi.

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="changeStream-code"></a>

Untuk melihat contoh kode untuk menggunakan tahap `$changeStream` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$cmp`Operator di Amazon DocumentDB digunakan untuk membandingkan dua nilai dan mengembalikan nilai integer yang menunjukkan urutan relatifnya. Ini adalah operator perbandingan yang membandingkan dua ekspresi dan mengembalikan nilai integer -1, 0, atau 1, tergantung pada apakah nilai pertama kurang dari, sama dengan, atau lebih besar dari nilai kedua, masing-masing.

**Parameter**
+ `expression1`: Ekspresi pertama untuk membandingkan.
+ `expression2`: Ekspresi kedua untuk membandingkan.

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

Contoh berikut menunjukkan penggunaan `$cmp` operator untuk membandingkan dua nilai numerik.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

Dalam contoh ini, `$cmp` operator membandingkan `value2` bidang `value1` dan untuk setiap dokumen. Hasilnya adalah:

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

## Contoh kode
<a name="cmp-code"></a>

Untuk melihat contoh kode untuk menggunakan `$cmp` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh penggunaan `$cmp` operator dalam aplikasi Node.js dengan `mongodb` driver:

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

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

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

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

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

  console.log(result);

  await client.close();
}

main();
```

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

Berikut adalah contoh penggunaan `$cmp` operator dalam aplikasi Python dengan driver: `pymongo`

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

Output dari contoh Node.js dan Python akan sama dengan contoh MongoDB Shell:

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

------

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

Baru dari versi 4.0

Tahap `$collStats` agregasi di Amazon DocumentDB menyediakan statistik tentang koleksi yang ditentukan, mirip dengan perintah di shell `db.collection.stats()` MongoDB. Tahap ini dapat digunakan untuk mengambil informasi tentang koleksi, seperti jumlah dokumen, ukuran total koleksi, dan berbagai metrik kinerja.

**Parameter**
+ `latencyStats`: (opsional) Dokumen yang menentukan opsi untuk mengumpulkan statistik latensi. Parameter ini tidak didukung di Amazon DocumentDB.
+ `recordStats`: (opsional) Dokumen yang menentukan opsi untuk mengumpulkan statistik catatan. Parameter ini tidak didukung di Amazon DocumentDB.
+ `queryExecStats`: (opsional) Sebuah dokumen yang menentukan pilihan untuk mengumpulkan statistik eksekusi query. Parameter ini tidak didukung di Amazon DocumentDB.

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

Contoh berikut menunjukkan bagaimana menggunakan tahap `$collStats` agregasi untuk mengambil statistik tentang koleksi bernama `test` dalam database. `db`

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="collStats-code"></a>

Untuk melihat contoh kode untuk menggunakan `$collStats` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh cara menggunakan tahap `$collStats` agregasi dalam aplikasi Node.js menggunakan driver MongoDB Node.js resmi:

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

Berikut adalah contoh cara menggunakan tahap `$collStats` agregasi dalam aplikasi Python menggunakan PyMongo driver:

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

run_coll_stats_example()
```

------

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

Operator `$concat` agregasi di Amazon DocumentDB menggabungkan (atau menggabungkan) beberapa string dalam dokumen untuk menghasilkan string tunggal yang dapat dikembalikan ke aplikasi. Ini mengurangi pekerjaan yang dilakukan dalam aplikasi, karena manipulasi string dilakukan di tingkat database.

**Parameter**
+ `expression1`: String pertama yang digabungkan.
+ `expression2`: String kedua untuk digabungkan.
+ `...`: String tambahan untuk digabungkan (opsional).

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

Dalam contoh ini, kami menggabungkan nama depan dan belakang pengguna untuk menghasilkan nama lengkap setiap orang.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="concat-code"></a>

Untuk melihat contoh kode untuk menggunakan `$concat` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$concatArrays` agregasi di Amazon DocumentDB digunakan untuk menggabungkan dua atau lebih array menjadi satu array. Ini dapat berguna ketika Anda perlu menggabungkan beberapa array data ke dalam satu array untuk pemrosesan atau analisis lebih lanjut.

**Parameter**
+ `array1`: Array pertama yang akan digabungkan.
+ `array2`: Array kedua yang akan digabungkan.
+ `[array3, ...]`: (opsional) Array tambahan yang akan digabungkan.

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

Contoh berikut menunjukkan bagaimana menggunakan `$concatArrays` operator untuk menggabungkan dua array ke dalam array tunggal.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="concatArrays-code"></a>

Untuk melihat contoh kode untuk menggunakan `$concatArrays` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await 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>

`$cond`Operator di Amazon DocumentDB digunakan untuk mengevaluasi ekspresi bersyarat dan mengembalikan salah satu dari dua ekspresi hasil yang mungkin.

**Parameter**
+ `if`: Ekspresi boolean untuk mengevaluasi.
+ `then`: Ekspresi untuk kembali jika `if` ekspresi benar.
+ `else`: Ekspresi untuk kembali jika `if` ekspresi salah.

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

Contoh berikut menunjukkan penggunaan `$cond` operator untuk mengembalikan nilai berdasarkan usia seseorang.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="cond-code"></a>

Untuk melihat contoh kode untuk menggunakan `$cond` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0

`$convert`Operator di Amazon DocumentDB digunakan untuk mengonversi nilai dari satu tipe data ke tipe data lainnya. Operator ini berguna ketika Anda perlu melakukan operasi pada data dari berbagai jenis, seperti mengubah string ke angka atau tanggal ke stempel waktu.

**Parameter**
+ `to`: Tipe data target untuk mengonversi nilainya menjadi. Nilai yang didukung adalah `"string"`, `"double"`, `"long"`, `"int"`, `"date"`, dan `"boolean"`.
+ `from`: Tipe data saat ini dari nilai. Jika tidak ditentukan, Amazon DocumentDB akan mencoba mendeteksi tipe data secara otomatis.
+ `onError`: (opsional) Nilai yang akan dikembalikan jika konversi gagal. Dapat berupa nilai tertentu atau salah satu dari nilai khusus berikut:`"null"`,`"zerofill"`, atau`"error"`.
+ `onNull`: (opsional) Nilai untuk kembali jika nilai masukan`null`. Dapat berupa nilai tertentu atau salah satu dari nilai khusus berikut:`"null"`,`"zerofill"`, atau`"error"`.

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

Contoh berikut menunjukkan konversi nilai string ke tanggal menggunakan operator. `$convert`

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="convert-code"></a>

Untuk melihat contoh kode untuk menggunakan `$convert` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect("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>

Tahap `$count` agregasi di Amazon DocumentDB digunakan untuk menghitung jumlah dokumen yang masuk ke panggung. Ini sering digunakan sebagai tahap akhir dalam pipa agregasi untuk mengembalikan jumlah total dokumen yang cocok dengan tahap sebelumnya.

**Parameter**
+ `field`: Bidang untuk dihitung. Parameter ini opsional, dan jika tidak disediakan, tahap akan menghitung jumlah total dokumen input.

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

Contoh berikut menunjukkan bagaimana menggunakan `$count` panggung untuk mendapatkan jumlah total dokumen dalam koleksi.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

Contoh agregat `users` koleksi dan menggunakan `$count` panggung untuk menghitung jumlah total dokumen.

## Contoh kode
<a name="count-code"></a>

Untuk melihat contoh kode untuk menggunakan `$count` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Tahap `$currentOp` agregasi mengembalikan informasi tentang operasi yang sedang berjalan dalam database. Tahap ini berguna untuk memantau kueri dan operasi aktif dalam jalur agregasi.

**Parameter**
+ `allUsers`(opsional): Ketika diatur ke`true`, mengembalikan operasi untuk semua pengguna. Default-nya adalah `false`.
+ `idleConnections`(opsional): Ketika diatur ke`true`, termasuk koneksi idle. Default-nya adalah `false`.
+ `idleCursors`(opsional): Ketika diatur ke`true`, termasuk informasi tentang kursor siaga. Default-nya adalah `false`.
+ `idleSessions`(opsional): Ketika diatur ke`true`, termasuk informasi tentang sesi idle. Default-nya adalah `true`.
+ `localOps`(opsional): Ketika diatur ke`true`, termasuk operasi lokal. Default-nya adalah `false`.

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

Contoh berikut menunjukkan menggunakan tahap `$currentOp` agregasi untuk mengambil informasi tentang operasi baca aktif.

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="currentOp-code"></a>

Untuk melihat contoh kode untuk menggunakan `$currentOp` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await 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()
```

------

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

Baru dari versi 5.0

Operator `$dateAdd` agregasi di Amazon DocumentDB memungkinkan Anda menambahkan durasi ke nilai tanggal dan waktu.

**Parameter**
+ `date`: Nilai tanggal dan waktu untuk menambahkan durasi.
+ `duration`: Durasi untuk menambah `date` nilai. Ini dapat ditentukan sebagai objek dengan kunci untuk`years`,`months`,`weeks`, `days``hours`,`minutes`, dan`seconds`.
+ `timezone`: (opsional) Zona waktu yang akan digunakan saat melakukan penambahan tanggal. Jika tidak ditentukan, zona waktu default cluster Amazon DocumentDB digunakan.

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

Contoh berikut menunjukkan bagaimana menggunakan `$dateAdd` operator untuk menambahkan 2 hari dan 12 jam ke tanggal.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="dateAdd-code"></a>

Untuk melihat contoh kode untuk menggunakan `$dateAdd` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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()
```

------

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

Baru dari versi 5.0

Tidak didukung oleh cluster elastis.

Operator `$dateDiff` agregasi menghitung perbedaan antara dua tanggal dalam satuan tertentu. Ini mengembalikan jumlah batas unit yang dilintasi antara tanggal mulai dan akhir.

**Parameter**
+ `startDate`: Ekspresi tanggal awal.
+ `endDate`: Ekspresi tanggal akhir.
+ `unit`: Satuan waktu untuk perbedaan. Unit yang didukung adalah `year``quarter`,`month`,`week`,`day`,`hour`,`minute`,`second`, dan`millisecond`.

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

Contoh berikut menunjukkan bagaimana menggunakan `$dateDiff` operator untuk menghitung jumlah hari antara penempatan pesanan dan pengiriman.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="dateDiff-code"></a>

Untuk melihat contoh kode untuk menggunakan `$dateDiff` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

Operator `$dateFromString` agregasi di Amazon DocumentDB memungkinkan Anda mengonversi string tanggal-waktu menjadi objek tanggal. Ini berguna ketika data Anda disimpan sebagai string tetapi Anda perlu melakukan operasi berbasis tanggal pada data.

**Parameter**
+ `dateString`: String yang mewakili tanggal dan waktu.
+ `format`: (opsional) Sebuah string yang menentukan format. `dateString` Jika tidak disediakan, Amazon DocumentDB akan mencoba mengurai string dalam format ISO-8601.
+ `timezone`: (opsional) Sebuah string yang menentukan zona waktu. Jika tidak disediakan, Amazon DocumentDB akan menggunakan zona waktu server.
+ `onError`: (opsional) Menentukan tindakan yang akan diambil jika konversi gagal. Nilai yang mungkin adalah `'error'` (default, yang melempar kesalahan), `'null'` (mengembalikan`null`), atau `'replace'` (menggantikan nilai dengan string pengganti yang ditentukan dalam `onErrorMessage` opsi).
+ `onErrorMessage`: (opsional) Jika `onError` diatur ke`'replace'`, opsi ini menentukan string pengganti.

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

Contoh berikut menunjukkan bagaimana menggunakan untuk mengkonversi string tanggal `$dateFromString` ke objek tanggal di Amazon DocumentDB.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="dateFromString-code"></a>

Untuk melihat contoh kode untuk menggunakan `$dateFromString` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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()
```

------

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

Baru dari versi 5.0

Operator `$dateSubtract` agregasi di Amazon DocumentDB memungkinkan Anda mengurangi durasi tertentu dari nilai tanggal.

**Parameter**
+ `date`: Ekspresi tanggal yang menyelesaikan tanggal atau stempel waktu.
+ `subtrahend`: Ekspresi durasi yang menentukan jumlah waktu untuk mengurangi dari ekspresi. `date`
+ `unit`: Sebuah string yang menentukan satuan waktu untuk `subtrahend` ekspresi. Unit yang didukung adalah “tahun”, “kuartal”, “bulan”, “minggu”, “hari”, “jam”, “menit”, “kedua”, dan “milidetik”.

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

Contoh berikut menunjukkan cara menggunakan `$dateSubtract` operator untuk menghitung tanggal satu tahun yang lalu dari tanggal saat ini.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="dateSubtract-code"></a>

Untuk melihat contoh kode untuk menggunakan `$dateSubtract` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

Operator `$dateToString` agregasi di Amazon DocumentDB digunakan untuk mengonversi nilai tanggal atau stempel waktu menjadi representasi string. Ini berguna ketika Anda perlu memformat tanggal dan waktu dengan cara tertentu untuk tampilan atau pemrosesan lebih lanjut.

**Parameter**
+ `date`: Nilai tanggal atau stempel waktu yang akan dikonversi ke string.
+ `format`: Sebuah string yang menentukan format di mana tanggal harus diwakili. String format dapat mencakup berbagai penentu format, seperti `%Y` untuk tahun empat digit, `%m` untuk bulan dua digit, `%d` untuk hari dua digit dalam sebulan, dll.
+ `timezone`: (opsional) Zona waktu yang akan digunakan untuk konversi. Jika tidak ditentukan, zona waktu server yang menghosting cluster Amazon DocumentDB digunakan.
+ `onNull`: (opsional) Nilai yang akan dikembalikan jika `date` parameternya`null`.

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

Contoh berikut menunjukkan penggunaan `$dateToString` operator untuk memformat `logDate` bidang `missionLog` koleksi.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="dateToString-code"></a>

Untuk melihat contoh kode untuk menggunakan `$dateToString` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh penggunaan `$dateToString` operator dalam aplikasi Node.js:

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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 ]

Berikut adalah contoh penggunaan `$dateToString` operator dalam aplikasi Python:

```
from pymongo import MongoClient

def example():
    client = 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()
```

------

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

Baru dari versi 8.0

Tidak didukung oleh cluster elastis.

Operator `$dateTrunc` agregasi di Amazon DocumentDB memotong tanggal ke unit tertentu.

**Parameter**
+ `date`: Ekspresi tanggal yang menyelesaikan tanggal atau stempel waktu.
+ `unit`: Sebuah string yang menentukan satuan waktu untuk ekspresi subtrahend. Unit yang didukung adalah `year``quarter`,`month`,,`week`,`day`,`hour`,`minute`,`second`, dan`millisecond`.

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

Contoh berikut menunjukkan cara menggunakan `$dateTrunc` operator untuk memotong tanggal ke jam.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="dateTrunc-code"></a>

Untuk melihat contoh kode untuk menggunakan `$dateTrunc` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

Operator `$dayOfMonth` agregasi di Amazon DocumentDB mengambil hari dalam sebulan (dari 1 hingga 31) untuk tanggal tertentu. Operator ini berguna untuk mengelompokkan, memfilter, atau mengekstrak hari dalam sebulan dari bidang tanggal dalam dokumen Anda.

**Parameter**
+ `date expression`: Ekspresi tanggal dapat berupa bidang tanggal dari dokumen, objek tanggal, atau string tanggal.

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

Contoh ini menunjukkan cara menggunakan `$dayOfMonth` operator untuk mengekstrak hari dalam sebulan dari bidang tanggal dalam dokumen.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="dayOfMonth-code"></a>

Untuk melihat contoh kode untuk menggunakan `$dayOfMonth` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

`$dayOfWeek`Operator di Amazon DocumentDB mengekstrak hari dalam seminggu dari bidang tanggal tertentu. Ini mengembalikan hari dalam seminggu sebagai angka antara 1 (Minggu) dan 7 (Sabtu), yang merupakan perilaku yang sama seperti di MongoDB.

**Parameter**
+ `date field`: Bidang tanggal untuk mengekstrak hari dalam seminggu dari.

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

Contoh ini menunjukkan cara menggunakan `$dayOfWeek` operator untuk mengekstrak hari dalam seminggu dari `date` bidang dalam `weather` koleksi.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="dayOfWeek-code"></a>

Untuk melihat contoh kode untuk menggunakan `$dayOfWeek` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$dayOfYear`Operator di Amazon DocumentDB mengembalikan hari dalam setahun untuk tanggal sebagai angka antara 1 dan 366 (365 dalam tahun non-kabisat).

**Parameter**
+ `expression`: Bidang tanggal atau ekspresi untuk mengekstrak hari dalam setahun.

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

Contoh ini menunjukkan cara menggunakan `$dayOfYear` operator untuk mengekstrak hari dalam setahun dari bidang tanggal dalam koleksi Amazon DocumentDB.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="dayOfYear-code"></a>

Untuk melihat contoh kode untuk menggunakan `$dayOfYear` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$divide`Operator di jalur agregasi Amazon DocumentDB digunakan untuk membagi satu nomor dengan yang lain. Ini adalah operator yang berguna untuk melakukan operasi matematika pada bidang numerik dalam dokumen Anda.

**Parameter**
+ `numerator`: Dividen atau nomor yang akan dibagi.
+ `denominator`: Pembagi atau nomor untuk dibagi dengan.

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

Contoh ini menunjukkan cara menggunakan `$divide` operator untuk menghitung tarif per jam untuk karyawan berdasarkan gaji tahunan mereka dan jumlah jam kerja per tahun.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="divide-code"></a>

Untuk melihat contoh kode untuk menggunakan `$divide` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$eq` agregasi membandingkan dua nilai dan kembali `true` jika mereka sama, jika tidak kembali. `false`

**Parameter**
+ `expression1`: Nilai pertama untuk membandingkan.
+ `expression2`: Nilai kedua untuk membandingkan.

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

Contoh berikut menunjukkan menggunakan `$eq` operator untuk memeriksa apakah jumlah produk cocok dengan nilai target.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="eq-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$eq` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0

`$exp`Operator di Amazon DocumentDB memungkinkan Anda menaikkan konstanta e ke nomor tertentu.

**Parameter**
+ `expression`: Ekspresi untuk mengevaluasi. Ini dapat berupa ekspresi agregasi yang valid, termasuk referensi bidang, operasi aritmatika, dan tahap agregasi lainnya.

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

Contoh berikut menunjukkan penggunaan `$exp` operator untuk menemukan semua dokumen di mana `quantity` bidang lebih besar dari `price` bidang.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="exp-code"></a>

Untuk melihat contoh kode untuk menggunakan `$exp` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$filter`Operator di Amazon DocumentDB digunakan untuk menerapkan ekspresi filter ke setiap elemen array dan mengembalikan array yang hanya berisi elemen yang cocok dengan kondisi yang ditentukan. Operator ini berguna ketika Anda perlu melakukan operasi penyaringan kompleks pada bidang array dalam dokumen Anda.

**Parameter**
+ `input`: Bidang array untuk menyaring.
+ `as`: Nama variabel yang digunakan untuk setiap elemen `input` array dalam `cond` ekspresi.
+ `cond`: Ekspresi boolean yang menentukan apakah elemen tertentu harus disertakan dalam array output.

## Contoh (MongoDB Shell)
<a name="filter-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$filter` operator untuk memproyeksikan pelanggan setiap pesanan dan membuat bidang array baru PaidItem berisi hanya item dari array item di mana harga lebih besar dari 15. Pada dasarnya, ini menyaring item setiap pesanan untuk memasukkan hanya produk yang harganya lebih dari 15.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="filter-code"></a>

Untuk melihat contoh kode untuk menggunakan `$filter` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Baru dari versi 5.0.

Tidak didukung oleh cluster elastis.

`$first`Operator di Amazon DocumentDB mengembalikan dokumen pertama dari kumpulan dokumen yang dikelompokkan. Hal ini biasanya digunakan dalam pipeline agregasi untuk mengambil dokumen pertama yang cocok dengan kondisi tertentu.

**Parameter**
+ `expression`: Ekspresi untuk kembali sebagai nilai pertama di setiap grup.

## Contoh (MongoDB Shell)
<a name="first-examples"></a>

Contoh berikut menunjukkan penggunaan `$first` operator untuk mengambil nilai item pertama yang ditemui untuk setiap kategori selama agregasi.

Catatan: `$first` mengembalikan dokumen pertama berdasarkan urutan dokumen saat ini dalam pipeline. Untuk memastikan pesanan tertentu (misalnya, berdasarkan tanggal, harga, dll.), `$sort` Tahap harus digunakan sebelum `$group` tahap.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="first-code"></a>

Untuk melihat contoh kode untuk menggunakan `$first` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Baru dari versi 4.0.

`$floor`Operator di Amazon DocumentDB mengembalikan bilangan bulat terbesar yang kurang dari atau sama dengan nomor yang ditentukan. Operator ini berguna untuk membulatkan nilai numerik.

**Parameter**
+ `expression`: Ekspresi numerik untuk membulatkan ke bawah.

## Contoh (MongoDB Shell)
<a name="floor-examples"></a>

Contoh berikut menunjukkan penggunaan `$floor` operator untuk membulatkan nilai desimal ke bilangan bulat terdekat.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="floor-code"></a>

Untuk melihat contoh kode untuk menggunakan `$floor` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Tahap `$geoNear` agregasi mengembalikan dokumen dalam urutan kedekatan dengan titik tertentu. Ini menghitung jarak dari titik dan termasuk jarak dalam dokumen output.

**Parameter**
+ `near`: Titik dari mana untuk menghitung jarak, ditentukan sebagai GeoJSON atau koordinat warisan.
+ `distanceField`: Nama bidang untuk menyimpan jarak yang dihitung.
+ `spherical`: Boolean menunjukkan apakah akan menggunakan geometri bola (diperlukan untuk titik GeoJSON).
+ `maxDistance`: Opsional. Jarak maksimum dari titik pusat.
+ `minDistance`: Opsional. Jarak minimum dari titik pusat.
+ `query`: Opsional. Kriteria filter tambahan untuk diterapkan.
+ `limit`: Opsional. Jumlah maksimum dokumen untuk dikembalikan.
+ `key`: Opsional. Bidang yang akan digunakan untuk kueri geospasial ketika beberapa indeks geospasial ada.

## Contoh (MongoDB Shell)
<a name="geoNear-examples"></a>

Contoh berikut menunjukkan menggunakan `$geoNear` panggung untuk menemukan toko terdekat dengan lokasi tertentu.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="geoNear-code"></a>

Untuk melihat contoh kode untuk menggunakan tahap `$geoNear` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Tahap `$group` agregasi di Amazon DocumentDB memungkinkan Anda mengelompokkan dokumen dengan ekspresi tertentu dan melakukan berbagai operasi akumulatif pada data yang dikelompokkan. Ini dapat berguna untuk tugas-tugas seperti menghitung total, rata-rata, atau statistik lain berdasarkan data yang dikelompokkan.

**Parameter**
+ `_id`: Menentukan ekspresi dimana dokumen masukan harus dikelompokkan. Ini bisa berupa nama bidang, ekspresi yang dihitung, atau kombinasi keduanya.
+ `accumulator expressions`: (opsional) Satu atau lebih ekspresi akumulator yang harus diterapkan pada data yang dikelompokkan. Ekspresi ini menggunakan operator akumulator yang disebutkan di atas.

## Contoh (MongoDB Shell)
<a name="group-examples"></a>

Contoh berikut mengelompokkan pelanggan berdasarkan kota mereka dan menghitung jumlah total pesanan untuk setiap kota.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="group-code"></a>

Untuk melihat contoh kode untuk menggunakan `$group` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$gt` agregasi membandingkan dua nilai dan kembali `true` jika nilai pertama lebih besar dari yang kedua, jika tidak kembali. `false`

**Parameter**
+ `expression1`: Nilai pertama untuk membandingkan.
+ `expression2`: Nilai kedua untuk membandingkan.

## Contoh (MongoDB Shell)
<a name="gt-aggregation-examples"></a>

Contoh berikut menunjukkan penggunaan `$gt` operator untuk mengidentifikasi produk yang melebihi ambang harga.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="gt-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$gt` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$gte` agregasi membandingkan dua nilai dan kembali `true` jika nilai pertama lebih besar dari atau sama dengan yang kedua, jika tidak kembali. `false`

**Parameter**
+ `expression1`: Nilai pertama untuk membandingkan.
+ `expression2`: Nilai kedua untuk membandingkan.

## Contoh (MongoDB Shell)
<a name="gte-aggregation-examples"></a>

Contoh berikut menunjukkan menggunakan `$gte` operator untuk memeriksa apakah siswa lulus ujian.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="gte-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$gte` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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`Operator mengekstrak komponen jam dari bidang tanggal atau stempel waktu.

**Parameter**
+ `dateExpression`: Tanggal penerapan operator. Ini harus diselesaikan ke tanggal BSON yang valid (misalnya, bidang seperti \$1createDat atau tanggal literal).

Parameter juga dapat ditentukan sebagai dokumen dalam format berikut:

\$1tanggal:`&lt;dateExpression&gt;`, zona waktu:`&lt;timezoneExpression&gt;`\$1

Ini memungkinkan untuk menerapkan operasi tanggal sadar zona waktu.

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

## Contoh (MongoDB Shell)
<a name="hour-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$hour` operator untuk mengekstrak komponen jam dari bidang tanggal dan mengelompokkan data yang sesuai.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

Kueri ini mengelompokkan peristiwa berdasarkan komponen jam `timestamp` bidang dan menghitung jumlah peristiwa untuk setiap jam.

## Contoh kode
<a name="hour-code"></a>

Untuk melihat contoh kode untuk menggunakan `$hour` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk mengembalikan nilai tertentu jika ekspresi input mengevaluasi ke null atau undefined. Operator ini dapat berguna dalam skenario di mana Anda ingin memberikan nilai default atau menangani null/undefined kasus.

**Parameter**
+ `expression`: Ekspresi untuk mengevaluasi.
+ `replacement`: Nilai untuk kembali jika `<expression>` mengevaluasi ke null atau undefined.

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

Contoh berikut menunjukkan penggunaan `$ifNull` operator untuk memberikan nilai default ketika `name` bidang adalah null atau undefined.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="ifNull-code"></a>

Untuk melihat contoh kode untuk menggunakan `$ifNull` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$in` agregasi memeriksa apakah nilai tertentu ada dalam array. Ia kembali `true` jika nilai ditemukan dalam array, dan `false` sebaliknya.

**Parameter**
+ `value`: Nilai untuk mencari.
+ `array`: Array untuk mencari di dalam.

## Contoh (MongoDB Shell)
<a name="in-aggregation-examples"></a>

Contoh berikut menunjukkan penggunaan `$in` operator untuk memeriksa apakah keterampilan tertentu ada dalam keahlian masing-masing karyawan.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="in-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$in` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$indexOfArray`Operator di Amazon DocumentDB digunakan untuk menemukan indeks kemunculan pertama elemen tertentu dalam array. Operator ini mengembalikan posisi indeks berbasis nol dari elemen pertama dalam array yang cocok dengan nilai yang ditentukan. Jika nilai tidak ditemukan, ia mengembalikan -1.

**Parameter**
+ `array`: Array untuk mencari.
+ `value`: Nilai untuk mencari dalam array.
+ `start`: (opsional) Posisi dalam array untuk memulai pencarian dari. Nilai default-nya adalah 0.

## Contoh (MongoDB Shell)
<a name="indexOfArray-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan indexOfArray operator \$1 untuk menemukan indeks kemunculan pertama elemen “mangga” dalam array “buah” untuk setiap dokumen.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="indexOfArray-code"></a>

Untuk melihat contoh kode untuk menggunakan `$indexOfArray` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

indexOfBytes Operator \$1 di Amazon DocumentDB digunakan untuk menemukan indeks awal substring dalam string, berdasarkan posisi byte karakter. Ini dapat berguna ketika bekerja dengan data teks yang mungkin berisi karakter multi-byte, seperti yang ditemukan dalam skrip non-Latin.

**Parameter**
+ `string`: String masukan untuk mencari.
+ `substring`: Substring untuk mencari dalam string input.
+ `[<start>]`: (opsional) Posisi awal (berbasis nol) pencarian. Jika tidak ditentukan, pencarian dimulai pada awal string.

## Contoh (MongoDB Shell)
<a name="indexOfBytes-examples"></a>

Contoh berikut menunjukkan penggunaan `$indexOfBytes` untuk menemukan indeks karakter tanda hubung pertama dalam satu set string yang mewakili lokasi meja.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="indexOfBytes-code"></a>

Untuk melihat contoh kode untuk menggunakan `$indexOfBytes` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

`$indexOfCP`Operator di Amazon DocumentDB digunakan untuk menemukan indeks, dalam titik kode (CP), dari kemunculan pertama substring tertentu dalam ekspresi string. Ini dapat berguna saat mengurai dan mengekstrak konten dari bidang string.

**Parameter**
+ `string expression`: String untuk mencari.
+ `substring`: Substring untuk mencari.
+ `[<start>]`: (opsional) Posisi untuk memulai pencarian (indeks berbasis nol). Default-nya adalah 0.

## Contoh (MongoDB Shell)
<a name="indexOfCP-examples"></a>

Dalam contoh ini, kami menggunakan `$indexOfCP` operator untuk menemukan indeks kemunculan pertama karakter tanda hubung - di bidang Desk setiap dokumen.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="indexOfCP-code"></a>

Untuk melihat contoh kode untuk menggunakan `$indexOfCP` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Tahap `$indexStats` agregasi di Amazon DocumentDB memberikan wawasan tentang penggunaan indeks dalam koleksi. Operator ini memungkinkan Anda memantau pola akses indeks Anda, yang dapat membantu Anda membuat keputusan berdasarkan informasi tentang manajemen dan pengoptimalan indeks.

**Parameter**

Tidak ada

## Contoh (MongoDB Shell)
<a name="indexStats-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$indexStats` operator untuk menganalisis penggunaan indeks dalam koleksi Amazon DocumentDB.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

Dalam contoh ini, `$indexStats` operator menunjukkan bahwa `_id_` indeks telah diakses 5 kali, dan `product_1` indeks telah diakses 10 kali sejak reset terakhir atau reboot server.

## Contoh kode
<a name="indexStats-code"></a>

Untuk melihat contoh kode untuk menggunakan `$indexStats` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$isArray`Operator di Amazon DocumentDB digunakan untuk memeriksa apakah bidang dalam dokumen adalah array. Operator ini dapat berguna dalam pipeline agregasi dan ekspresi bersyarat untuk menangani bidang tipe array.

**Parameter**
+ `field`: Jalur bidang untuk memeriksa apakah itu adalah array.

## Contoh (MongoDB Shell)
<a name="isArray-examples"></a>

Contoh ini menunjukkan cara menggunakan `$isArray` operator untuk mengidentifikasi dokumen di mana bidang “inventaris” adalah array.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="isArray-code"></a>

Untuk melihat contoh kode untuk menggunakan `$isArray` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

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

  const result = await collection.aggregate([
    {
      $match: {
        $isArray: '$inventory'
      }
    },
    {
      $project: {
        _id: 1,
        name: 1,
        "inventory.location": 1,
        "inventory.count": 1
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

run();
```

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

```
from pymongo import MongoClient

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

result = list(collection.aggregate([
    {
        '$match': {
            '$isArray': '$inventory'
        }
    },
    {
        '$project': {
            '_id': 1,
            'name': 1,
            'inventory.location': 1,
            'inventory.count': 1
        }
    }
]))

print(result)

client.close()
```

------

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

`$isoDayOfWeek`Operator di Amazon DocumentDB mengembalikan hari ISO dalam seminggu untuk tanggal sebagai nilai integer. Sistem tanggal minggu ISO mendefinisikan setiap minggu dimulai pada hari Senin dan berakhir pada hari Minggu, dengan minggu 1 menjadi minggu yang berisi Kamis pertama tahun itu.

**Parameter**
+ `expression`: Ekspresi tanggal untuk mengembalikan hari ISO dalam seminggu.

## Contoh (MongoDB Shell)
<a name="isoDayOfWeek-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$isoDayOfWeek` operator untuk mengambil hari ISO dalam seminggu untuk satu set dokumen acara.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="isoDayOfWeek-code"></a>

Untuk melihat contoh kode untuk menggunakan `$isoDayOfWeek` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

`$isoWeek`Operator di Amazon DocumentDB mengembalikan nomor minggu ISO untuk tanggal. Sistem tanggal minggu ISO adalah cara penomoran minggu dalam setahun, di mana minggu pertama tahun baru adalah minggu yang berisi Kamis pertama tahun itu. Ini berbeda dengan kalender Gregorian, di mana minggu pertama tahun baru adalah minggu yang berisi 1 Januari.

**Parameter**

Tidak ada

## Contoh (MongoDB Shell)
<a name="isoWeek-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$isoWeek` operator untuk mengambil nomor minggu ISO untuk tanggal tertentu.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="isoWeek-code"></a>

Untuk melihat contoh kode untuk menggunakan `$isoWeek` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$isoWeekYear`Operator di Amazon DocumentDB mengembalikan nomor tahun ISO 8601 minggu untuk tanggal tertentu. Nomor tahun minggu ISO berbeda dari tahun kalender Gregorian karena tahun minggu dapat berbeda dari tahun kalender, terutama pada awal dan akhir tahun.

**Parameter**
+ `expression`: Ekspresi tanggal untuk mengembalikan nomor tahun ISO 8601 minggu.

## Contoh (MongoDB Shell)
<a name="isoWeekYear-examples"></a>

Contoh ini menunjukkan cara menggunakan `$isoWeekYear` operator untuk mengambil tahun ISO 8601 minggu untuk bidang tanggal setiap dokumen dalam koleksi peristiwa.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="isoWeekYear-code"></a>

Untuk melihat contoh kode untuk menggunakan `$isoWeekYear` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

`$last`Operator di Amazon DocumentDB digunakan untuk mengembalikan elemen terakhir dalam array yang cocok dengan kriteria kueri. Hal ini sangat berguna untuk mengambil elemen terbaru atau terakhir dalam array yang memenuhi kondisi tertentu.

**Parameter**
+ `expression`: Ekspresi untuk mencocokkan elemen array.

## Contoh (MongoDB Shell)
<a name="last-examples"></a>

Contoh berikut menunjukkan penggunaan `$last` operator dalam kombinasi dengan `$filter` untuk mengambil elemen terakhir dari array yang memenuhi kondisi tertentu (misalnya, subjek adalah 'sains').

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="last-code"></a>

Untuk melihat contoh kode untuk menggunakan `$last` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$let`Operator di Amazon DocumentDB digunakan untuk mengikat variabel ke nilai dan menggunakan variabel tersebut dalam ekspresi. Ini memungkinkan Anda untuk menentukan variabel lokal yang dapat digunakan dalam ekspresi berikutnya dalam tahap yang sama dari pipa agregasi.

**Parameter**
+ `vars`: Objek yang mendefinisikan variabel yang akan digunakan dalam ekspresi.
+ `in`: Ekspresi di mana variabel yang didefinisikan dalam parameter vars digunakan.

## Contoh (MongoDB Shell)
<a name="let-examples"></a>

Contoh ini menunjukkan penggunaan `$let` operator untuk menghitung luas persegi panjang.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="let-code"></a>

Untuk melihat contoh kode untuk menggunakan `$let` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$limit`Operator di Amazon DocumentDB digunakan untuk membatasi jumlah dokumen yang dikembalikan oleh kueri. Ini mirip dengan operator `$limit` MongoDB, tetapi ada beberapa pertimbangan khusus saat menggunakannya dengan Amazon DocumentDB.

Di Amazon DocumentDB, `$limit` operator berguna untuk pagination, di mana Anda ingin mengambil subset dari total dokumen yang cocok. Ini memungkinkan Anda untuk mengontrol jumlah dokumen yang dikembalikan dalam setiap respons, meningkatkan kinerja dan mengurangi jumlah data yang ditransfer melalui jaringan.

**Parameter**
+ `limit`: Jumlah maksimum dokumen untuk dikembalikan. Ini harus berupa nilai integer non-negatif.

## Contoh (MongoDB Shell)
<a name="limit-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$limit` operator untuk mengembalikan maksimal satu dokumen yang cocok dengan filter yang diberikan.

**Buat dokumen sampel**

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

**Contoh kueri**

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

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

**Keluaran**

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

## Contoh kode
<a name="limit-code"></a>

Untuk melihat contoh kode untuk menggunakan `$limit` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$literal`Operator di Amazon DocumentDB digunakan untuk mewakili nilai literal dalam tahap pipeline agregasi. Ini memungkinkan Anda untuk memasukkan nilai tertentu, seperti angka, string, atau boolean, tanpa menafsirkannya sebagai referensi bidang atau ekspresi.

Operator ini sangat berguna ketika Anda perlu menyertakan nilai literal sebagai bagian dari pipeline agregasi yang lebih kompleks, seperti saat membuat filter kueri dinamis atau melakukan perhitungan.

**Parameter**

Tidak ada

## Contoh (MongoDB Shell)
<a name="literal-examples"></a>

Contoh berikut menunjukkan penggunaan `$literal` operator untuk menyertakan nilai literal dalam pipeline agregasi. `$literal`Operator digunakan untuk memasukkan nilai 18 sebagai nilai literal dalam ekspresi \$1gt. Hal ini memungkinkan jalur agregasi untuk membandingkan bidang usia dengan nilai literal 18 untuk menentukan apakah orang tersebut dewasa.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="literal-code"></a>

Untuk melihat contoh kode untuk menggunakan `$literal` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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()
```

------

# \$1In
<a name="ln"></a>

Baru dari versi 4.0.

`$ln`Operator di Amazon DocumentDB menghitung logaritma natural (basis e) dari nomor tertentu. Ia mengembalikan logaritma angka ke basis e.

**Parameter**
+ `expression`: Angka yang logaritma natural akan dihitung.

## Contoh (MongoDB Shell)
<a name="ln-examples"></a>

Contoh berikut menunjukkan penggunaan `$log` operator untuk menghitung logaritma natural dari suatu angka.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="ln-code"></a>

Untuk melihat contoh kode untuk menggunakan `$ln` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0.

`$log`Operator di Amazon DocumentDB menghitung logaritma natural dari suatu angka. Ia mengembalikan logaritma basis-e dari nomor yang ditentukan.

**Parameter**
+ `expression`: Angka yang logaritma natural akan dihitung.
+ `base`: Nilai dasar untuk menghitung log.

## Contoh (MongoDB Shell)
<a name="log-examples"></a>

Contoh berikut menunjukkan penggunaan `$log` operator untuk menghitung logaritma natural dari suatu angka.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="log-code"></a>

Untuk melihat contoh kode untuk menggunakan `$log` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0.

`$log10`Operator di Amazon DocumentDB digunakan untuk menghitung logaritma basis-10 dari suatu angka. Hal ini berguna untuk melakukan perhitungan logaritmik pada bidang numerik dalam pipeline agregasi.

**Parameter**
+ `expression`: Ekspresi numerik yang logaritma basis-10 akan dihitung.

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

Contoh berikut menunjukkan bagaimana menggunakan `$log10` operator untuk menghitung logaritma basis-10 dari bidang numerik.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="log10-code"></a>

Untuk melihat contoh kode untuk menggunakan `$log10` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$lt` agregasi membandingkan dua nilai dan kembali `true` jika nilai pertama kurang dari yang kedua, jika tidak kembali. `false`

**Parameter**
+ `expression1`: Nilai pertama untuk membandingkan.
+ `expression2`: Nilai kedua untuk membandingkan.

## Contoh (MongoDB Shell)
<a name="lt-aggregation-examples"></a>

Contoh berikut menunjukkan menggunakan `$lt` operator untuk mengidentifikasi item stok rendah.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="lt-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$lt` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$lte` agregasi membandingkan dua nilai dan kembali `true` jika nilai pertama kurang dari atau sama dengan yang kedua, jika tidak kembali. `false`

**Parameter**
+ `expression1`: Nilai pertama untuk membandingkan.
+ `expression2`: Nilai kedua untuk membandingkan.

## Contoh (MongoDB Shell)
<a name="lte-aggregation-examples"></a>

Contoh berikut menunjukkan penggunaan `$lte` operator untuk mengidentifikasi item yang ramah anggaran.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="lte-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$lte` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Tahap `$lookup` agregasi di Amazon DocumentDB memungkinkan Anda melakukan gabungan luar kiri antara dua koleksi. Operasi ini memungkinkan Anda menggabungkan data dari beberapa koleksi berdasarkan nilai bidang yang cocok. Ini sangat berguna ketika Anda perlu memasukkan data dari koleksi terkait ke dalam hasil kueri Anda.

**Parameter**
+ `from`: Nama koleksi untuk melakukan bergabung dengan.
+ `localField`: Bidang dari dokumen masukan untuk mencocokkan dengan`foreignField`.
+ `foreignField`: Bidang dari dokumen dalam `from` koleksi untuk dicocokkan dengan`localField`.
+ `as`: Nama bidang baru untuk ditambahkan ke dokumen keluaran yang berisi dokumen yang cocok dari `from` koleksi.

## Contoh (MongoDB Shell)
<a name="lookup-examples"></a>

Contoh berikut menunjukkan `$lookup` operasi sederhana yang menggabungkan data dari `orders` koleksi ke dalam koleksi. `customers`

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="lookup-code"></a>

Untuk melihat contoh kode untuk menggunakan `$lookup` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function 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>

Baru dari versi 4.0.

Tidak didukung oleh cluster elastis.

`$ltrim`Operator di Amazon DocumentDB digunakan untuk menghapus karakter utama dari string. Secara default, ini menghapus karakter spasi utama, tetapi Anda juga dapat menentukan satu set karakter untuk dihapus dengan meneruskan argumen karakter.

**Parameter**
+ `input`: String masukan dari mana untuk menghapus karakter spasi utama.
+ `chars`: (opsional) Untuk menghapus karakter tertentu.

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

Contoh berikut menunjukkan penggunaan `$ltrim` untuk menghapus karakter tertentu (“\$1”) dari awal string.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="ltrim-code"></a>

Untuk melihat contoh kode untuk menggunakan `$ltrim` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function 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>

`$map`Operator di Amazon DocumentDB memungkinkan Anda menerapkan ekspresi tertentu ke setiap elemen dalam array dan mengembalikan array baru dengan elemen yang diubah. Operator ini sangat berguna untuk memanipulasi dan mengubah data dalam array, yang dapat membantu menyederhanakan kode aplikasi Anda dan meningkatkan kinerja kueri dengan mendorong pemrosesan array ke tingkat database.

**Parameter**
+ `input`: Array yang akan diubah.
+ `as`: (opsional) Nama variabel yang akan digunakan dalam ekspresi in untuk mewakili elemen saat ini sedang diproses.
+ `in`: Ekspresi yang akan diterapkan untuk setiap elemen dalam array input.

## Contoh (MongoDB Shell)
<a name="map-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan operator \$1map untuk mengubah array angka, menggandakan setiap nilai.

**Buat dokumen sampel**

```
db.collection.insertMany([
  { _id: 1, numbers: [1, 2, 3, 4, 5] },
  { _id: 2, numbers: [10, 20, 30, 40, 50] }
])
```

**Contoh kueri**

```
db.collection.aggregate([
  {
    $project: {
      doubledNumbers: { $map: { input: "$numbers", as: "num", in: { $multiply: ["$$num", 2] } } }
    }
  }
])
```

**Keluaran**

```
[
  { _id: 1, doubledNumbers: [2, 4, 6, 8, 10] },
  { _id: 2, doubledNumbers: [20, 40, 60, 80, 100] }
]
```

## Contoh kode
<a name="map-code"></a>

Untuk melihat contoh kode untuk menggunakan `$map` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Tahap `$match` pipeline di Amazon DocumentDB digunakan untuk memfilter dokumen input hanya ke dokumen yang cocok dengan kriteria kueri yang ditentukan. Ini adalah salah satu tahapan pipa yang paling umum digunakan dalam operasi agregasi. `$match`Tahap ini diterapkan sebelum tahap pipa lainnya, memungkinkan Anda untuk secara efisien mengurangi jumlah dokumen yang perlu diproses oleh tahap selanjutnya.

**Parameter**
+ `query`: Dokumen yang menyatakan kriteria seleksi untuk operasi. Dokumen query menggunakan sintaks yang sama dengan `find()` metode.

## Contoh (MongoDB Shell)
<a name="match-examples"></a>

Contoh berikut menunjukkan penggunaan `$match` panggung untuk memfilter dokumen berdasarkan nilai bidang tertentu.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.collection.aggregate([
  { $match: { age: { $gt: 30 } } },
  { $project: { _id: 1, name: 1, city: 1 } }
]);
```

**Keluaran**

```
[
  { "_id": 3, "name": "Bob", "city": "Chicago" },
  { "_id": 4, "name": "Alice", "city": "Miami" }
]
```

`$match`Tahap menyaring dokumen untuk memasukkan hanya yang `age` bidangnya lebih besar dari 30.

## Contoh kode
<a name="match-code"></a>

Untuk melihat contoh kode untuk menggunakan `$match` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Tahap `$max` agregasi digunakan untuk mengembalikan nilai maksimum bidang tertentu di semua dokumen dalam tahap pipeline. Operator ini berguna untuk menemukan nilai tertinggi dalam satu set dokumen.

**Parameter**
+ `expression`: Ekspresi yang digunakan untuk menghitung nilai maksimum.

## Contoh (MongoDB Shell)
<a name="max-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$max` operator untuk menemukan skor maksimum dalam koleksi dokumen siswa. `$group`Tahap mengelompokkan semua dokumen bersama-sama, dan `$max` operator digunakan untuk menghitung nilai maksimum `score` bidang di semua dokumen.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.students.aggregate([
  { $group: { _id: null, maxScore: { $max: "$score" } } },
  { $project: { _id: 0, maxScore: 1 } }
])
```

**Keluaran**

```
[ { maxScore: 92 } ]
```

## Contoh kode
<a name="max-code"></a>

Untuk melihat contoh kode untuk menggunakan `$max` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$meta` agregasi mengakses metadata yang terkait dengan dokumen dalam pipeline agregasi. Hal ini biasanya digunakan untuk mengambil skor pencarian teks dan mengurutkan hasil berdasarkan relevansi.

**Parameter**
+ `textScore`: Mengambil skor pencarian teks yang menunjukkan relevansi dokumen dengan permintaan pencarian.

## Contoh (MongoDB Shell)
<a name="meta-aggregation-examples"></a>

Contoh berikut menunjukkan penggunaan `$meta` operator dalam pipeline agregasi untuk mengambil dan mengurutkan berdasarkan skor pencarian teks.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.articles.aggregate([
  { $match: { $text: { $search: "Python" } } },
  { $addFields: { score: { $meta: "textScore" } } },
  { $sort: { score: -1 } }
]);
```

**Keluaran**

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

## Contoh kode
<a name="meta-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$meta` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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()
```

------

# \$1 bergabung
<a name="merge"></a>

Diperkenalkan pada 8.0

Tahap `$merge` agregasi di Amazon DocumentDB digunakan untuk menggabungkan hasil tahap pipeline sebelumnya ke dalam pengumpulan target. Ini berguna untuk memperbarui atau menyisipkan dokumen dalam koleksi target berdasarkan data dari dokumen masukan.

`$merge`Tahap ini memungkinkan Anda untuk melakukan berbagai tindakan berdasarkan kondisi pencocokan antara dokumen input dan pengumpulan target, seperti:

```
- Insert new documents
- Update existing documents
- Delete documents
- Fail the operation if there are any conflicts
```

**Parameter**
+ `into`: (wajib) Nama koleksi target untuk menggabungkan dokumen masukan ke dalam.
+ `on`: (wajib) Bidang yang akan digunakan sebagai kondisi yang cocok antara dokumen masukan dan pengumpulan target.
+ `whenMatched`: (opsional) Tindakan yang harus dilakukan ketika dokumen input cocok dengan dokumen yang ada dalam koleksi target. Nilai yang didukung adalah:`"merge"`,`"replace"`,`"keepExisting"`, dan`"fail"`.
+ `whenNotMatched`: (opsional) Tindakan yang harus dilakukan ketika dokumen input tidak cocok dengan dokumen apa pun dalam koleksi target. Nilai yang didukung adalah: `"insert"` dan`"fail"`.

## Contoh (MongoDB Shell)
<a name="merge-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$merge` tahap untuk memperbarui `users` koleksi dengan data baru dari pipeline input.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.inputData.aggregate([
  {
    $merge: {
      into: "users",
      on: "_id",
      whenMatched: "merge",
      whenNotMatched: "insert"
    }
  }
])
```

**Keluaran**

Setelah menjalankan `$merge` pipeline, `users` koleksi akan berisi dokumen-dokumen berikut:

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

## Contoh kode
<a name="merge-code"></a>

Untuk melihat contoh kode untuk menggunakan `$merge` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh penggunaan operator \$1merge dalam aplikasi Node.js:

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

async function example() {
  const client = await MongoClient.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 ]

Berikut adalah contoh menggunakan operator \$1merge dalam aplikasi Python:

```
from pymongo import MongoClient

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

`$mergeObjects`Operator di Amazon DocumentDB digunakan untuk menggabungkan beberapa dokumen atau objek ke dalam satu dokumen. Operator ini sangat berguna ketika Anda perlu menggabungkan konten dari dua atau lebih dokumen atau objek, berpotensi menimpa nilai dari satu objek dengan yang dari yang lain.

**Parameter**
+ `expression1`: Objek pertama yang akan digabungkan.
+ `expression2`: (opsional) Objek kedua yang akan digabungkan.
+ `expression3`: (opsional) Objek tambahan yang akan digabungkan.

## Contoh (MongoDB Shell)
<a name="mergeObjects-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$mergeObjects` operator untuk menggabungkan dua objek.

**Buat dokumen sampel**

```
db.collection.insertMany([
  { "_id": 1, "name": "John", "address": { "city": "New York", "state": "NY" } },
  { "_id": 2, "name": "Jane", "address": { "city": "Los Angeles", "state": "CA" } }
]);
```

**Contoh kueri**

```
db.collection.aggregate([
  {
    $project: {
      "combinedAddress": {
        $mergeObjects: ["$address", { "country": "USA" }]
      }
    }
  }
])
```

**Keluaran**

```
[
  {
    "_id": 1,
    "combinedAddress": {
      "city": "New York",
      "state": "NY",
      "country": "USA"
    }
  },
  {
    "_id": 2,
    "combinedAddress": {
      "city": "Los Angeles",
      "state": "CA",
      "country": "USA"
    }
  }
]
```

## Contoh kode
<a name="mergeObjects-code"></a>

Untuk melihat contoh kode untuk menggunakan `$mergeObjects` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$millisecond`Operator di Amazon DocumentDB digunakan untuk mengekstrak bagian milidetik dari nilai tanggal.

**Parameter**

Tidak ada

## Contoh (MongoDB Shell)
<a name="millisecond-examples"></a>

Contoh ini menunjukkan bagaimana menggunakan `$millisecond` operator untuk mengekstrak bagian milidetik dari nilai tanggal.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.events.aggregate([
  {
    $project: {
      name: 1,
      milliseconds: { $millisecond: "$timestamp" }
    }
  }
])
```

**Keluaran**

```
[
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c1"),
    "name": "Event 1",
    "milliseconds": 123
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c2"),
    "name": "Event 2",
    "milliseconds": 456
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c3"),
    "name": "Event 3",
    "milliseconds": 789
  }
]
```

## Contoh kode
<a name="millisecond-code"></a>

Untuk melihat contoh kode untuk menggunakan `$millisecond` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator mengembalikan nilai minimum dari array nilai. Ini dapat digunakan dalam tahap agregasi untuk menemukan nilai minimum untuk bidang tertentu di beberapa dokumen.

**Parameter**
+ `expression`: Ekspresi untuk mengevaluasi. Ini bisa berupa jalur bidang, variabel, atau ekspresi apa pun yang menyelesaikan nilai.

## Contoh (MongoDB Shell)
<a name="min-examples"></a>

Contoh berikut menunjukkan penggunaan `$min` operator untuk menemukan nilai minimum `age` bidang di beberapa dokumen.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.users.aggregate([
  { $group: { _id: null, minAge: { $min: "$age" } } },
  { $project: { _id: 0, minAge: 1 } }
])
```

**Keluaran**

```
[ { minAge: 28 } ]
```

## Contoh kode
<a name="min-code"></a>

Untuk melihat contoh kode untuk menggunakan `$min` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Tahap pipeline `$minute` agregasi di Amazon DocumentDB mengekstrak nilai menit dari bidang tanggal atau stempel waktu.

Operator ini berguna saat Anda perlu melakukan perhitungan atau pengelompokan berbasis tanggal dan waktu dalam jalur agregasi Anda.

**Parameter**
+ `expression`: Bidang tanggal atau stempel waktu untuk mengekstrak nilai menit.

## Contoh (MongoDB Shell)
<a name="minute-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$minute` operator untuk mengelompokkan dokumen dengan nilai menit yang diekstrak dari bidang stempel waktu dan menghitung jumlah dokumen di setiap grup.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

```
[
  { "_id": { "minute": 30 }, "count": 2 },
  { "_id": { "minute": 31 }, "count": 2 },
  { "_id": { "minute": 32 }, "count": 1 }
]
```

## Contoh kode
<a name="minute-code"></a>

Untuk melihat contoh kode untuk menggunakan `$minute` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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`Operator adalah operator aritmatika yang melakukan operasi modulo pada angka. Ia mengembalikan sisa membagi satu nomor dengan yang lain. Operator ini biasanya digunakan untuk menentukan apakah suatu bilangan ganjil atau genap, atau untuk mendistribusikan item ke dalam jumlah grup yang terbatas.

**Parameter**
+ `expression1`: Ekspresi dividen.
+ `expression2`: Ekspresi pembagi.

## Contoh (MongoDB Shell)
<a name="mod-examples"></a>

Contoh ini menunjukkan bagaimana menggunakan `$mod` operator untuk menentukan jumlah widget sisa saat pengiriman dalam paket 100.

**Buat dokumen sampel**

```
db.widgets.insertMany([
  { "_id" : 1, "widget" : "A", "count" : 80372 },
  { "_id" : 2, "widget" : "B", "count" : 409282 },
  { "_id" : 3, "widget" : "C", "count" : 60739 }
])
```

**Contoh kueri**

```
db.widgets.aggregate([
  { $addFields: { leftOver: { $mod: [ "$count", 100 ] } } }
])
```

**Keluaran**

```
[
  { "_id" : 1, "widget" : "A", "count" : 80372, "leftOver" : 72 },
  { "_id" : 2, "widget" : "B", "count" : 409282, "leftOver" : 82 },
  { "_id" : 3, "widget" : "C", "count" : 60739, "leftOver" : 39 }
]
```

Output menunjukkan sisa `count` dibagi dengan 100 untuk setiap dokumen, yang mewakili jumlah widget sisa saat pengiriman dalam paket 100.

## Contoh kode
<a name="mod-code"></a>

Untuk melihat contoh kode untuk menggunakan `$mod` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$month`Operator di Amazon DocumentDB mengembalikan bulan tanggal sebagai angka antara 1 dan 12. Operator ini berguna untuk mengekstrak komponen bulan dari bidang tanggal dan melakukan agregasi dan analisis berbasis tanggal.

**Parameter**
+ `date_expression`: Ini adalah ekspresi atau bidang yang berisi tanggal atau stempel waktu dari mana Anda ingin mengekstrak bulan.

## Contoh (MongoDB Shell)
<a name="month-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$month` operator untuk mengekstrak bulan dari bidang tanggal dan mengelompokkan data berdasarkan bulan.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.sales.aggregate([
  { $group: { 
      _id: { month: { $month: "$date" } },
      totalSales: { $sum: "$price" }
    }},
  { $sort: { "_id.month": 1 } }
]);
```

**Keluaran**

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

## Contoh kode
<a name="month-code"></a>

Untuk melihat contoh kode untuk menggunakan `$month` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$multiply`Operator di Amazon DocumentDB digunakan untuk melipatgandakan nilai dua atau lebih bidang atau ekspresi. Operator ini sangat berguna untuk melakukan operasi aritmatika pada bidang numerik dalam dokumen. Ini dapat digunakan dalam berbagai tahap pipa agregasi, seperti `$project` dan`$addFields`, untuk membuat bidang baru atau memodifikasi yang sudah ada.

**Parameter**
+ `expression1`: Ekspresi numerik pertama yang akan dikalikan.
+ `expression2`: Ekspresi numerik kedua yang akan dikalikan.
+ `[expression3, ...]`: (opsional) Ekspresi numerik tambahan yang akan dikalikan.

## Contoh (MongoDB Shell)
<a name="multiply-examples"></a>

Contoh berikut menunjukkan penggunaan `$multiply` untuk menghitung `bonus_miles` dengan mengalikan `base_miles` dan `bonus_rate` untuk pelanggan yang menggunakan kartu kredit untuk perjalanan.

**Contoh dokumen**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="multiply-code"></a>

Untuk melihat contoh kode untuk menggunakan `$multiply` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$natural`Operator di Amazon DocumentDB digunakan untuk mengurutkan dokumen dalam urutan alami mereka, yang merupakan urutan di mana mereka dimasukkan ke dalam koleksi. Ini berbeda dengan perilaku penyortiran default, yaitu mengurutkan dokumen berdasarkan nilai bidang yang ditentukan.

**Parameter**

Tidak ada

## Contoh (MongoDB Shell)
<a name="natural-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$natural` operator untuk mengurutkan dokumen dalam koleksi dalam urutan alami mereka.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.people.find({}, { "_id": 1, "name": 1 }).sort({ "$natural": 1 });
```

**Keluaran**

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

Kueri mengurutkan dokumen dalam koleksi dalam urutan alami mereka, yang merupakan urutan di mana mereka dimasukkan.

## Contoh kode
<a name="natural-code"></a>

Untuk melihat contoh kode untuk menggunakan `$natural` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$ne` agregasi membandingkan dua nilai dan kembali `true` jika mereka tidak sama, jika tidak kembali. `false`

**Parameter**
+ `expression1`: Nilai pertama untuk membandingkan.
+ `expression2`: Nilai kedua untuk membandingkan.

## Contoh (MongoDB Shell)
<a name="ne-aggregation-examples"></a>

Contoh berikut menunjukkan menggunakan `$ne` operator untuk mengidentifikasi pesanan dengan perubahan status.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      status: 1,
      expectedStatus: 1,
      needsAttention: { $ne: ["$status", "$expectedStatus"] }
    }
  }
]);
```

**Keluaran**

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

## Contoh kode
<a name="ne-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$ne` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$not` agregasi melakukan operasi NOT logis pada ekspresi. Ia kembali `true` jika ekspresi mengevaluasi`false`, dan `false` jika ekspresi mengevaluasi untuk. `true`

**Parameter**
+ `expression`: Ekspresi untuk meniadakan.

## Contoh (MongoDB Shell)
<a name="not-aggregation-examples"></a>

Contoh berikut menunjukkan menggunakan `$not` operator untuk membalikkan nilai boolean.

**Buat dokumen sampel**

```
db.users.insertMany([
  { _id: 1, name: "Alice", active: true },
  { _id: 2, name: "Bob", active: false },
  { _id: 3, name: "Charlie", active: true }
]);
```

**Contoh kueri**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      active: 1,
      inactive: { $not: ["$active"] }
    }
  }
]);
```

**Keluaran**

```
[
  { _id: 1, name: 'Alice', active: true, inactive: false },
  { _id: 2, name: 'Bob', active: false, inactive: true },
  { _id: 3, name: 'Charlie', active: true, inactive: false }
]
```

## Contoh kode
<a name="not-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$not` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$objectToArray` agregasi di Amazon DocumentDB mengubah objek (atau dokumen) menjadi array. Masukan ke operator adalah dokumen, dan output terdiri dari elemen array untuk setiap pasangan nilai bidang dalam dokumen input. Operator ini berguna ketika Anda perlu bekerja dengan masing-masing bidang dokumen sebagai array, seperti ketika Anda ingin menemukan dokumen dengan nilai maksimum atau minimum untuk bidang tertentu.

**Parameter**
+ `expression`: Ekspresi dokumen untuk dikonversi menjadi array.

## Contoh (MongoDB Shell)
<a name="objectToArray-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$objectToArray` operator untuk menemukan dokumen dengan inventaris maksimum untuk rantai toko penyewaan video.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.videos.aggregate([
  {
    $project: {
      name: 1,
      videos: {
        $objectToArray: "$inventory"
      }
    }
  },
  {
    $unwind: "$videos"
  },
  {
    $group: {
      _id: "$name",
      maxInventory: {
        $max: "$videos.v"
      }
    }
  }
]);
```

**Keluaran**

```
[
  {
    "_id": "Bravemind",
    "maxInventory": 1000
  },
  {
    "_id": "Live Soft",
    "maxInventory": 1000
  },
  {
    "_id": "Romancing the Rock",
    "maxInventory": 500
  },
  {
    "_id": "Top Pilot",
    "maxInventory": 1000
  }
]
```

## Contoh kode
<a name="objectToArray-code"></a>

Untuk melihat contoh kode untuk menggunakan `$objectToArray` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$or` agregasi mengevaluasi beberapa ekspresi dan mengembalikan `true` jika setidaknya satu ekspresi mengevaluasi. `true` Ia kembali `false` hanya jika semua ekspresi`false`.

**Parameter**
+ `expressions`: Sebuah array ekspresi untuk mengevaluasi.

## Contoh (MongoDB Shell)
<a name="or-aggregation-examples"></a>

Contoh berikut menunjukkan penggunaan `$or` operator untuk memeriksa apakah produk memenuhi salah satu dari beberapa kriteria.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.items.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      onSale: 1,
      goodDeal: {
        $or: [
          { $lt: ["$price", 50] },
          { $eq: ["$onSale", true] }
        ]
      }
    }
  }
]);
```

**Keluaran**

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

## Contoh kode
<a name="or-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$or` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$out`Operator di Amazon DocumentDB digunakan untuk menulis hasil pipeline agregasi ke koleksi tertentu.

`$out`harus menjadi tahap terakhir dalam pipa.

**Parameter**
+ `output_collection`: Nama koleksi keluaran untuk menulis hasil agregasi ke.

**Catatan**: Jika koleksi sudah ada, maka akan diganti dengan hasil tahap agregasi.

## Contoh (MongoDB Shell)
<a name="out-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$out` operator di Amazon DocumentDB untuk menulis hasil pipeline agregasi ke koleksi baru.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.products.aggregate([
  { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
  { $out: "product_categories" }
])
```

**Keluaran**

Tidak ada (hasilnya ditulis ke koleksi output).

Pipa agregasi mengelompokkan produk berdasarkan kategori dan menghitung harga total item untuk setiap kategori. `$out`Operator menulis hasilnya ke koleksi baru bernama “product\$1categories”.

**Untuk melihat hasil dalam koleksi output:**

```
db.product_categories.find()
[
{ "_id" : "Books", "totalPrice" : 125 },
{ "_id" : "Electronics", "totalPrice" : 300 }
]
```

## Contoh kode
<a name="out-code"></a>

Untuk melihat contoh kode untuk menggunakan `$out` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Diperkenalkan pada 8.0

`$pow`Operator di Amazon DocumentDB memungkinkan Anda menaikkan angka ke daya. Ini dapat berguna untuk melakukan perhitungan eksponensial dalam pipeline agregasi Anda.

**Parameter**
+ `<number>`(wajib): Angka yang akan dinaikkan menjadi kekuatan.
+ `<exponent>`(wajib): Kekuatan yang harus dinaikkan nomor tersebut.

## Contoh (MongoDB Shell)
<a name="pow-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$pow` operator untuk menghitung kuadrat angka.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.numbers.aggregate([
  { $addFields: { "square": { $pow: ["$value", 2] } } }
])
```

**Keluaran**

```
[
  { "_id": 1, "value": 2, "square": 4 },
  { "_id": 2, "value": 3, "square": 9 },
  { "_id": 3, "value": 4, "square": 16 }
]
```

## Contoh kode
<a name="pow-code"></a>

Untuk melihat contoh kode untuk menggunakan `$pow` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh menggunakan operator \$1pow dalam aplikasi Node.js:

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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 ]

Berikut adalah contoh menggunakan operator \$1pow dalam aplikasi Python:

```
from pymongo import MongoClient

def example():
    client = 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>

Operator `$push` agregasi mengembalikan array dari semua nilai dari ekspresi tertentu untuk setiap kelompok. Hal ini biasanya digunakan dalam `$group` tahap untuk mengakumulasi nilai-nilai ke dalam array.

**Parameter**
+ `expression`: Ekspresi untuk mengevaluasi setiap dokumen dalam grup.

## Contoh (MongoDB Shell)
<a name="push-aggregation-examples"></a>

Contoh berikut menunjukkan menggunakan `$push` operator untuk mengumpulkan semua nama produk untuk setiap kategori.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.sales.aggregate([
  {
    $group: {
      _id: "$category",
      products: { $push: "$product" }
    }
  }
]);
```

**Keluaran**

```
[
  { _id: 'Furniture', products: [ 'Desk', 'Chair' ] },
  { _id: 'Electronics', products: [ 'Laptop', 'Mouse', 'Keyboard' ] }
]
```

## Contoh kode
<a name="push-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$push` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$project`Operator di Amazon DocumentDB memungkinkan Anda untuk secara selektif menyertakan atau mengecualikan bidang dari dokumen keluaran, meneruskan nilai ke tahap pipeline berikutnya, dan menghitung bidang baru dari nilai dokumen masukan.

**Parameter**
+ `field`: Bidang untuk menyertakan atau mengecualikan dari dokumen output, dapat berupa jalur bidang (misalnya, “a.b.c”).
+ `1`atau`true`: Termasuk bidang dalam output.
+ `0`atau`false`: Mengecualikan bidang dari output.

## Contoh (MongoDB Shell)
<a name="project-examples"></a>

Contoh berikut menunjukkan penggunaan `$project` operator pada koleksi siswa

**Buat dokumen sampel**

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

Kueri ini hanya mencakup `name` dan `math` bidang dalam output. `_id`Bidang disertakan secara default kecuali secara eksplisit dikecualikan.

```
db.students.aggregate([
  { $project: { "name": 1, "math": 1 } }
])
```

**Keluaran**

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

Kueri ini mengecualikan `grade` dan `_id` bidang dari output, menampilkan semua bidang lainnya (`name`,`math`,`science`).

```
db.students.aggregate([
  { $project: { "grade": 0, "_id": 0 } }
])
```

**Keluaran**

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

## Contoh kode
<a name="project-code"></a>

Untuk melihat contoh kode untuk menggunakan `$project` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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()
```

------

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

Baru dari versi 8.0

`$rand`Operator di Amazon DocumentDB digunakan untuk menghasilkan angka acak antara 0 dan 1.

**Parameter**

Tidak ada

## Contoh (MongoDB Shell)
<a name="rand-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$rand` operator untuk secara acak memilih dua dokumen dari koleksi. `temp`

**Buat dokumen sampel**

```
db.items.insertMany([
  { "name": "pencil", "quantity": 110 },
  { "name": "pen", "quantity": 159 }
])
```

**Contoh kueri**

```
db.items.aggregate([
  {
    $project: {
      randomValue: { $rand: {} }
    }
  }
])
```

**Keluaran**

```
[
  {
    _id: ObjectId('6924a5edd66dcae121d29517'),
    randomValue: 0.8615243955294392
  },
  {
    _id: ObjectId('6924a5edd66dcae121d29518'),
    randomValue: 0.22815483022099903
  }
]
```

## Contoh kode
<a name="rand-code"></a>

Untuk melihat contoh kode untuk menggunakan `$rand` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$range` agregasi di Amazon DocumentDB digunakan untuk membuat array angka berurutan dalam rentang tertentu. Operator ini sangat berguna untuk menghasilkan urutan angka, seperti penanda mil untuk stasiun bantuan dalam perlombaan, seperti yang ditunjukkan dalam contoh di bawah ini.

**Parameter**
+ `start`: Nilai awal untuk rentang.
+ `end`: Nilai akhir untuk rentang.
+ `step`: (opsional) Nilai langkah yang akan digunakan saat menghasilkan rentang. Jika tidak disediakan, nilai langkah default adalah 1.

## Contoh (MongoDB Shell)
<a name="range-examples"></a>

Dalam contoh ini, kita akan menggunakan `$range` operator untuk menghasilkan penanda mil untuk stasiun air dalam perlombaan sepeda.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.races.aggregate([
  {
    $project: {
      race: 1,
      "waterStations": { $range: [20, "$distance", 20] }
    }
  }
]);
```

**Keluaran**

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

## Contoh kode
<a name="range-code"></a>

Untuk melihat contoh kode untuk menggunakan `$range` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function 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>

Tahap `$redact` agregasi di Amazon DocumentDB digunakan untuk secara selektif menyertakan atau mengecualikan konten dari dokumen keluaran berdasarkan nilai bidang tertentu. Ini sangat berguna dalam skenario di mana Anda perlu mengontrol visibilitas data sensitif berdasarkan tingkat akses atau izin pengguna.

**Parameter**
+ `$cond`: Ekspresi yang mengevaluasi salah satu`$$KEEP`,`$$PRUNE`, atau `$$DESCEND` untuk setiap bidang dalam dokumen.
+ `$$KEEP`: Mempertahankan bidang saat ini dalam dokumen output.
+ `$$PRUNE`: Menghapus bidang saat ini dari dokumen output.
+ `$$DESCEND`: Secara rekursif menerapkan `$redact` tahap ke bidang saat ini, yang merupakan objek atau array.

## Contoh (MongoDB Shell)
<a name="redact-examples"></a>

Dalam contoh ini, kita akan menggunakan `$redact` tahap untuk memfilter pesanan berdasarkan statusnya, hanya menampilkan pesanan dengan nilai status tertentu.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.orders.aggregate([
  {
    $redact: {
      $cond: {
        if: { $in: ["$status", ["shipped", "processing"]] },
        then: "$$KEEP",
        else: "$$PRUNE"
      }
    }
  }
])
```

**Keluaran**

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

Dalam contoh ini, `$redact` tahap memeriksa nilai `status` bidang di setiap dokumen. Jika “`status`dikirim” atau “diproses”, dokumen disimpan (`$$KEEP`). Jika tidak, dokumen dipangkas (`$$PRUNE`).

## Contoh kode
<a name="redact-code"></a>

Untuk melihat contoh kode untuk menggunakan `$redact` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$reduce` agregasi di Amazon DocumentDB digunakan untuk menerapkan fungsi dua argumen secara kumulatif ke elemen array untuk mengurangi array menjadi satu nilai. Operator ini sangat berguna untuk melakukan perhitungan atau transformasi kompleks pada data array dalam pipeline agregasi.

**Parameter**
+ `input`: Array yang akan dikurangi.
+ `initialValue`: Nilai awal yang akan digunakan dalam operasi reduksi.
+ `in`: Ekspresi yang akan dievaluasi pada setiap elemen `input` array. Ekspresi ini harus mengembalikan nilai yang akan digunakan dalam iterasi reduksi berikutnya.

## Contoh (MongoDB Shell)
<a name="reduce-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$reduce` operator untuk menghitung jumlah semua elemen dalam array.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.orders.aggregate([
  {
    $project: {
      total: {
        $reduce: {
          input: "$items",
          initialValue: 0,
          in: { $add: ["$$value", "$$this"] }
        }
      }
    }
  }
])
```

**Keluaran**

```
[
  { "_id": 1, "total": 15 },
  { "_id": 2, "total": 60 },
  { "_id": 3, "total": 80 },
  { "_id": 4, "total": 300 }
]
```

`$reduce`Operator iterasi atas `items` array, menambahkan setiap elemen ke `initialValue` 0. Hasilnya adalah jumlah semua elemen dalam array.

## Contoh kode
<a name="reduce-code"></a>

Untuk melihat contoh kode untuk menggunakan `$reduce` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh penggunaan `$reduce` operator dalam aplikasi 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 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 ]

Berikut adalah contoh penggunaan `$reduce` operator dalam aplikasi 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"]
    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>

Baru dari versi 5.0.

Tidak didukung oleh cluster elastis.

`$regexFind`Operator di Amazon DocumentDB digunakan untuk melakukan pencocokan ekspresi reguler pada bidang string dalam dokumen. Ini memungkinkan Anda untuk mencari dan mengekstrak substring tertentu yang cocok dengan pola ekspresi reguler yang diberikan.

**Parameter**
+ `input`: Bidang string atau ekspresi untuk mencari.
+ `regex`: Pola ekspresi reguler untuk mencocokkan.
+ `options`: (opsional) Objek yang menentukan parameter opsional untuk ekspresi reguler, seperti sensitivitas huruf kecil dan pencocokan multi-baris. Opsi yang didukung adalah `i` (case-insensitive) dan `m` (multi-line).

## Contoh (MongoDB Shell)
<a name="regexFind-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$regexFind` operator untuk mencari dokumen di mana `name` bidang cocok dengan pola ekspresi reguler tertentu.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.users.aggregate([
  {
    $project: {
      names: {
        $regexFind: { input: '$name', regex: 'j', options: 'i' }
      }
    }
  },
  { $match: {names: {$ne: null}}}
])
```

Kueri ini akan mengembalikan semua dokumen di mana `name` bidang berisi huruf “j” (case-insensitive).

**Keluaran**

```
[
  { _id: 1, names: { match: 'J', idx: 0, captures: [] } }
]
```

**Catatan:** Jika kueri Anda menggunakan Amazon DocumentDB planner versi 1, Anda harus menggunakan petunjuk untuk menggunakan indeks. Tanpa petunjuk, kueri dapat melakukan pemindaian koleksi. Untuk memeriksa versi perencana dan mempelajari lebih lanjut tentang menggunakan petunjuk, lihat [Dokumentasi Amazon DocumentDB Query Planner] (-planner.html). https://docs.aws.amazon.com/documentdb/ latest/developerguide/query

## Contoh kode
<a name="regexFind-code"></a>

Untuk melihat contoh kode untuk menggunakan `$regexFind` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Diperkenalkan pada 5.0

`$regexFindAll`Operator di Amazon DocumentDB digunakan untuk melakukan pencocokan ekspresi reguler pada bidang string dalam dokumen. Ini memungkinkan Anda untuk mencari dan mengekstrak substring tertentu yang cocok dengan pola ekspresi reguler yang diberikan, mengembalikan semua kecocokan ekspresi reguler.

**Parameter**
+ `input`: Bidang string atau ekspresi untuk mencari.
+ `regex`: Pola ekspresi reguler untuk mencocokkan.
+ `options`: (opsional) Objek yang menentukan parameter opsional untuk ekspresi reguler, seperti sensitivitas huruf kecil dan pencocokan multi-baris. Opsi yang didukung adalah `i` (case-insensitive) dan `m` (multi-line).

## Contoh (MongoDB Shell)
<a name="regexFindAll-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$regexFindAll` operator untuk mengekstrak semua urutan huruf dari lapangan. `email`

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      emailMatches: {
        $regexFindAll: { input: '$email', regex: '[a-z]+', options: 'i' }
      }
    }
  }
])
```

**Keluaran**

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

**Catatan:** Jika kueri Anda menggunakan Amazon DocumentDB planner versi 1, Anda harus menggunakan petunjuk untuk menggunakan indeks. Tanpa petunjuk, kueri dapat melakukan pemindaian koleksi. Untuk memeriksa versi perencana dan mempelajari lebih lanjut tentang menggunakan petunjuk, lihat [Dokumentasi Amazon DocumentDB Query Planner] (-planner.html). https://docs.aws.amazon.com/documentdb/ latest/developerguide/query

## Contoh kode
<a name="regexFindAll-code"></a>

Untuk melihat contoh kode untuk menggunakan `$regexFindAll` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh penggunaan `$regexFind` operator dalam aplikasi 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: {
        name: 1,
        emailMatches: {
          $regexFindAll: { input: "$email", regex: "[a-z]+", options: "i" }
        }
      }
    }
  ]).toArray();
  
  console.log(JSON.stringify(results, null, 2));

  await client.close();
}

main();
```

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

Berikut adalah contoh penggunaan `$regexFind` operator dalam aplikasi 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": { 
            "name": 1,
            "emailMatches": { 
                "$regexFindAll": { 
                    "input": "$email", 
                    "regex": "[a-z]+", 
                    "options": "i" 
                }
            }
        }
    }
]))

print(results)

client.close()
```

------

# \$1RegexMatch
<a name="regexMatch"></a>

Baru dari versi 5.0. Tidak didukung oleh cluster elastis.

`$regexMatch`Operator di Amazon DocumentDB digunakan untuk melakukan pencocokan ekspresi reguler pada bidang string. Ia mengembalikan nilai boolean (`true`atau`false`) menunjukkan apakah string input cocok dengan pola yang ditentukan.

**Parameter**
+ `input`: String untuk menguji terhadap ekspresi reguler.
+ `regex`: Pola ekspresi reguler untuk mencocokkan.
+ `options`: (Opsional) Bendera untuk mengubah perilaku ekspresi reguler, seperti pencocokan case-insensitive (`i`) atau pencocokan multiline (). `m`

## Contoh (MongoDB Shell)
<a name="regexMatch-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$regexMatch` operator untuk memeriksa apakah nama dimulai dengan huruf 'M'. Operator mengembalikan `true` atau `false` untuk setiap dokumen.

**Buat dokumen sampel**

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

]);
```

**Contoh kueri**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      startsWithM: {
        $regexMatch: {
          input: "$name",
          regex: "^M",
          options: "i"
        }
      }
    }
  }
]);
```

**Keluaran**

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

## Contoh kode
<a name="regexMatch-code"></a>

Untuk melihat contoh kode untuk menggunakan `$regexMatch` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------

# \$1 GantiSemua
<a name="replaceAll"></a>

Diperkenalkan pada 5.0

`$replaceAll`Operator di Amazon DocumentDB digunakan untuk mengganti semua kemunculan pola string tertentu dalam bidang dengan string baru. Operator ini dapat berguna untuk tugas-tugas seperti normalisasi data, pembersihan teks, dan manipulasi string.

**Parameter**
+ `input`: Bidang atau ekspresi yang berisi string yang akan diganti.
+ `find`: Pola string untuk mencari dan mengganti.
+ `replacement`: String untuk mengganti kejadian yang cocok dengan.

## Contoh (MongoDB Shell)
<a name="replaceAll-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$replaceAll` operator dalam pipeline agregasi untuk mengganti semua kemunculan string “Chocolatier” dengan “Chocolate Co.” di bidang “BrandName” dari koleksi “produk”.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.products.aggregate([
  {
    $addFields: {
      "brandName": {
        $replaceAll: {
          input: "$brandName",
          find: "Chocolatier",
          replacement: "Chocolate Co."
        }
      }
    }
  }
])
```

**Keluaran**

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

## Contoh kode
<a name="replaceAll-code"></a>

Untuk melihat contoh kode untuk menggunakan `$replaceAll` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------

# \$1 GantiSatu
<a name="replaceOne"></a>

Diperkenalkan pada 5.0

`$replaceOne`Operator di Amazon DocumentDB adalah operator ekspresi string yang digunakan dalam pipeline agregasi untuk menggantikan kemunculan pertama substring tertentu dalam string dengan string pengganti. Operator ini peka huruf besar/kecil dan hanya menggantikan kecocokan pertama yang ditemukan.

**Parameter**
+ `input`: String (bidang) untuk melakukan pencarian.
+ `find`: String untuk mencari di dalam input.
+ `replacement`: String untuk menggantikan kemunculan pertama dari temuan di input (field).

## Contoh (MongoDB Shell)
<a name="replaceOne-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$replaceOne` operator dalam pipeline agregasi untuk mengganti substring dalam nama produk.

**Buat dokumen sampel**

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

**Contoh agregasi**

```
db.products.aggregate([
  {
    $addFields: {
      standardizedName: {
        $replaceOne: {
          input: "$name",
          find: "Pack",
          replacement: "Package"
        }
      }
    }
  }
]);
```

**Keluaran**

Output menunjukkan bahwa hanya kemunculan pertama “Pack” di setiap nama produk diganti dengan “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"
  }
```

## Contoh kode
<a name="replaceOne-code"></a>

Untuk melihat contoh kode untuk menggunakan `$replaceOne` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk mengganti dokumen root dengan dokumen tertanam yang ditentukan. Ini berguna ketika Anda ingin mempromosikan dokumen bersarang ke tingkat atas atau merestrukturisasi output data Anda.

**Parameter**
+ `newRoot`: Dokumen root baru yang akan menggantikan dokumen root yang ada.

## Contoh (MongoDB Shell)
<a name="replaceRoot-examples"></a>

Contoh ini menunjukkan cara mengekstrak informasi alamat pengiriman dari pesanan pelanggan, yang berguna untuk menghasilkan label pengiriman atau daftar alamat.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.orders.aggregate([
  {
    $replaceRoot: {
      newRoot: "$shippingAddress"
    }
  }
])
```

**Keluaran**

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

## Contoh kode
<a name="replaceRoot-code"></a>

Untuk melihat contoh kode untuk menggunakan `$replaceRoot` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------

# \$1 GantiDengan
<a name="replaceWith"></a>

Baru dari versi 8.0

Tidak didukung oleh cluster elastis.

Tahap `$replaceWith` agregasi di Amazon DocumentDB digunakan untuk mengganti dokumen input dengan dokumen baru. Semua bidang yang ada pada dokumen masukan, termasuk bidang \$1id, diganti dengan dokumen baru. `$replaceWith`biasanya digunakan untuk meratakan dokumen, atau mempromosikan dokumen tertanam ke tingkat atas.

**Parameter**
+ `<replacement>`(wajib): Dokumen baru yang akan menggantikan dokumen yang ada.

## Contoh (MongoDB Shell)
<a name="replaceWith-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$replaceWith` operator untuk mengganti dokumen yang ada dalam koleksi Amazon DocumentDB.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.restaurants.aggregate([
  { $replaceWith: {
      name: "$name",
      cuisine: "$cuisine",
      rating: { $avg: "$ratings" }
    }
  }
]);
```

**Keluaran**

```
[
  {
    name: 'Biryani Adda',
    cuisine: 'Indian',
    rating: 3.4
  },
  {
    name: 'The Burger Spot',
    cuisine: 'American',
    rating: 2.7777777777777777
  }
]
```

## Contoh kode
<a name="replaceWith-code"></a>

Untuk melihat contoh kode untuk menggunakan `$replaceWith` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$reverseArray`Operator di Amazon DocumentDB digunakan untuk membalikkan elemen array dalam urutan yang ditentukan. Operator ini berguna ketika Anda perlu menyusun ulang elemen array dalam arah sebaliknya.

**Parameter**
+ `expression`: Ekspresi array untuk membalikkan.

## Contoh (MongoDB Shell)
<a name="reverseArray-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$reverseArray` operator untuk membalikkan urutan elemen dalam array.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.miles.aggregate([
  {
    $project: {
      _id: 1,
      member_since: 1,
      credit_card: 1,
      reversed_flight_miles: { $reverseArray: "$flight_miles" }
    }
  }
]);
```

**Keluaran**

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

Dalam contoh ini, `$reverseArray` operator digunakan untuk membalikkan urutan `flight_miles` array. `reversed_flight_miles`Bidang yang dihasilkan dalam output menunjukkan elemen array dalam urutan terbalik.

## Contoh kode
<a name="reverseArray-code"></a>

Untuk melihat contoh kode untuk menggunakan `$reverseArray` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh penggunaan `$reverseArray` operator dalam aplikasi Node.js:

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

Berikut adalah contoh penggunaan `$reverseArray` operator dalam aplikasi Python:

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

Baru dari versi 4.0.

Tidak didukung oleh cluster elastis.

`$rtrim`Operator di Amazon DocumentDB digunakan untuk menghapus karakter trailing dari string. Secara default, ini menghapus karakter spasi tambahan, tetapi Anda juga dapat menentukan satu set karakter yang akan dihapus dengan meneruskan argumen karakter.

**Parameter**
+ `input`: String masukan dari mana untuk menghapus karakter spasi belakang.
+ `chars`: (opsional) Untuk menghapus karakter tertentu.

## Contoh (MongoDB Shell)
<a name="rtrim-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$rtrim` operator untuk menghapus trailing karakter tertentu (“\$1”) dari string.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="rtrim-code"></a>

Untuk melihat contoh kode untuk menggunakan `$rtrim` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Tahap `$sample` agregasi di Amazon DocumentDB digunakan untuk memilih secara acak sejumlah dokumen tertentu dari koleksi. Ini berguna untuk tugas-tugas seperti analisis data, pengujian, dan menghasilkan sampel untuk diproses lebih lanjut.

**Parameter**
+ `size`: Jumlah dokumen untuk dipilih secara acak.

## Contoh (MongoDB Shell)
<a name="sample-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$sample` panggung untuk secara acak memilih dua dokumen dari koleksi. `temp`

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.temp.aggregate([
   { $sample: { size: 2 } }
])
```

**Keluaran**

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

Seperti yang ditunjukkan hasil, 2 dari 10 dokumen diambil sampelnya secara acak. Anda sekarang dapat menggunakan dokumen-dokumen ini untuk menentukan rata-rata atau untuk melakukan min/max perhitungan.

## Contoh kode
<a name="sample-code"></a>

Untuk melihat contoh kode untuk menggunakan `$sample` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------

# \$1 pencarian
<a name="search"></a>

Baru dari versi 5.0.

`$search`Operator di Amazon DocumentDB digunakan untuk menyediakan kemampuan pencarian teks.

**Parameter**

Tidak ada

## Contoh (MongoDB Shell)
<a name="search-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$search` operator untuk melakukan query pencarian teks.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.textcollection.find(
  { $text: { $search: "John" } }
);
```

**Keluaran**

```
[
  {
    _id: 1,
    name: 'John Doe',
    description: 'This is a sample document about John Doe.'
  }
]
```

## Contoh kode
<a name="search-code"></a>

Untuk melihat contoh kode untuk menggunakan `$search` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$second`Operator di Amazon DocumentDB mengekstrak komponen detik dari tanggal atau stempel waktu. Ini digunakan untuk mengambil nilai detik dari bidang tanggal atau timestamp.

**Parameter**
+ `expression`: Bidang tanggal atau stempel waktu untuk mengekstrak nilai detik dari. Ekspresi ini dapat berupa jalur bidang atau ekspresi valid apa pun yang menyelesaikan tanggal atau stempel waktu.

## Contoh (MongoDB Shell)
<a name="second-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$second` operator untuk mengekstrak komponen detik dari bidang tanggal.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.users.aggregate([{ $project: { name: 1, dobSeconds: { $second: "$dob" } } }])
```

**Keluaran**

```
[
  { "_id" : ObjectId("6089a9c306a829d1f8b456a1"), "name" : "John", "dobSeconds" : 45 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a2"), "name" : "Jane", "dobSeconds" : 59 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a3"), "name" : "Bob", "dobSeconds" : 0 }
]
```

## Contoh kode
<a name="second-code"></a>

Untuk melihat contoh kode untuk menggunakan `$second` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

Baru dari versi 8.0

Tidak didukung oleh cluster elastis.

Tahap `$set` agregasi di Amazon DocumentDB memungkinkan Anda menambahkan bidang baru atau memperbarui nilai bidang yang ada dalam dokumentasi selama pipeline agregasi.

**Parameter**
+ `expression`: Ekspresi untuk mengevaluasi. Ini bisa berupa ekspresi agregasi yang valid, termasuk referensi bidang dan operasi aritmatika.

## Contoh (MongoDB Shell)
<a name="set-stage-examples"></a>

Contoh berikut menunjukkan penggunaan tahap `$set` agregasi untuk menghitung total dengan mengalikan bidang dengan bidang. `quantity` `price`

**Buat dokumen sampel**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**Contoh agregasi**

```
db.inventory.aggregate([
  {
    $set: {
      total: { $multiply: ["$quantity", "$price"] }
    }
  }
])
```

**Keluaran**

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

## Contoh kode
<a name="set-stage-code"></a>

Untuk melihat contoh kode untuk menggunakan `$set` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

Baru dari versi 4.0.

`$setDifference`Operator di Amazon DocumentDB digunakan untuk membandingkan dua set dan mengembalikan elemen yang ada di set pertama tetapi tidak di set kedua. Operator ini berguna untuk menemukan elemen unik antara dua set.

**Parameter**
+ `firstSet`: Set pertama untuk membandingkan.
+ `secondSet`: Set kedua untuk membandingkan.

## Contoh (MongoDB Shell)
<a name="setDifference-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$setDifference` operator untuk menemukan elemen unik antara dua set.

**Buat dokumen sampel**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry", "date"] },
  { _id: 2, fruits: ["banana", "cherry", "date", "elderberry"] }
]);
```

**Contoh kueri**

```
db.collection.aggregate([
  {
    $project: {
      uniqueFruits: { $setDifference: ["$fruits", ["banana", "cherry", "date"]] }
    }
  }
]);
```

**Keluaran**

```
[
  { "_id": 1, "uniqueFruits": ["apple"] },
  { "_id": 2, "uniqueFruits": ["elderberry"] }
]
```

Kueri melakukan langkah-langkah berikut:

1. Ini menggunakan `$project` panggung untuk membuat bidang baru `uniqueFruits` untuk setiap dokumen.

2. `$setDifference`Operator membandingkan `fruits` array dengan array `[&quot;banana&quot;, &quot;cherry&quot;, &quot;date&quot;]` dan mengembalikan elemen unik dalam `fruits` array.

## Contoh kode
<a name="setDifference-code"></a>

Untuk melihat contoh kode untuk menggunakan `$setDifference` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh cara menggunakan `$setDifference` operator dalam aplikasi 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('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 ]

Berikut adalah contoh cara menggunakan `$setDifference` operator dalam aplikasi 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['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>

`$setEquals`Operator di Amazon DocumentDB digunakan untuk menentukan apakah dua set sama. Ini membandingkan dua array dan kembali `true` jika mengandung elemen berbeda yang sama, terlepas dari urutannya.

**Parameter**
+ `expression1`: Array pertama untuk membandingkan.
+ `expression2`: Array kedua untuk membandingkan.

## Contoh (MongoDB Shell)
<a name="setEquals-examples"></a>

Contoh berikut menunjukkan penggunaan `$setEquals` operator untuk membandingkan dua set nilai.

**Buat dokumen sampel**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry"] },
  { _id: 2, fruits: ["banana", "apple", "cherry"] },
  { _id: 3, fruits: ["apple", "banana", "orange"] }
])
```

**Contoh kueri**

```
db.collection.find({
  $expr: {
    $setEquals: ["$fruits", ["apple", "banana", "cherry"]]
  }
})
```

**Keluaran**

```
{ "_id" : 1, "fruits" : [ "apple", "banana", "cherry" ] }
{ "_id" : 2, "fruits" : [ "banana", "apple", "cherry" ] }
```

Query menggunakan `$setEquals` operator untuk membandingkan `fruits` bidang setiap dokumen dengan array`[&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]`. Dokumen di mana `fruits` bidang sama dengan array perbandingan dikembalikan.

## Contoh kode
<a name="setEquals-code"></a>

Untuk melihat contoh kode untuk menggunakan `$setEquals` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$setIntersection`Operator di Amazon DocumentDB digunakan untuk mengembalikan elemen umum antara dua atau lebih array. Operator ini sangat berguna saat bekerja dengan set data, memungkinkan Anda menemukan persimpangan beberapa set.

**Parameter**
+ `array1`: Array pertama untuk berpotongan.
+ `array2`: Array kedua untuk berpotongan.
+ `arrayN`: (opsional) Array tambahan untuk berpotongan.

## Contoh (MongoDB Shell)
<a name="setIntersection-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$setIntersection` operator untuk menemukan elemen umum antara dua array.

**Buat dokumen sampel**

```
db.collection.insertMany([
  { _id: 1, colors: ["red", "blue", "green"] },
  { _id: 2, colors: ["blue", "yellow", "orange"] },
  { _id: 3, colors: ["red", "green", "purple"] }
])
```

**Contoh kueri**

```
db.collection.aggregate([
  { $project: {
      _id: 1,
      commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
    }
  }
])
```

**Keluaran**

```
[
  { "_id": 1, "commonColors": ["red", "blue", "green"] },
  { "_id": 2, "commonColors": ["blue"] },
  { "_id": 3, "commonColors": ["red", "green"] }
]
```

## Contoh kode
<a name="setIntersection-code"></a>

Untuk melihat contoh kode untuk menggunakan `$setIntersection` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$setIsSubset`Operator di Amazon DocumentDB digunakan untuk menentukan apakah satu set nilai adalah subset dari himpunan lain. Hal ini berguna untuk melakukan perbandingan berbasis set dan operasi pada bidang array.

**Parameter**
+ `field`: Bidang untuk menerapkan `$setIsSubset` operator ke.
+ `set`: Set untuk membandingkan bidang terhadap.

## Contoh (MongoDB Shell)
<a name="setIsSubset-examples"></a>

Contoh berikut menunjukkan penggunaan `$setIsSubset` operator untuk memeriksa apakah `tags` bidang adalah subset dari set yang ditentukan.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.products.find({
  $expr: { $setIsSubset: [["tag1", "tag2"], "$tags"] }
})
```

\$1Catatan: \$1 `$setIsSubset` adalah operator agregasi dan tidak dapat digunakan secara langsung dalam kueri find (). Dalam contoh ini, `$expr` digunakan dengan `find()` untuk menjembatani kesenjangan antara operator query dan ekspresi agregasi.

**Keluaran**

```
[
  { "_id" : 1, "name" : "Product A", "tags" : [ "tag1", "tag2", "tag3" ] },
  { "_id" : 2, "name" : "Product B", "tags" : [ "tag1", "tag2" ] }
]
```

Query mengembalikan dokumen di mana `tags` bidang adalah bagian dari himpunan`[&quot;tag1&quot;, &quot;tag2&quot;]`.

## Contoh kode
<a name="setIsSubset-code"></a>

Untuk melihat contoh kode untuk menggunakan `$setIsSubset` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$setUnion` agregasi di Amazon DocumentDB digunakan untuk menggabungkan dua atau lebih set nilai dan mengembalikan satu set yang berisi semua elemen unik dari set input. Operator ini berguna ketika Anda perlu melakukan operasi berbasis set pada bidang array dalam dokumen Anda.

**Parameter**
+ `expression1`: Ekspresi yang menyelesaikan ke array.
+ `expression2`: Ekspresi yang menyelesaikan ke array.
+ `expressionN`: Ekspresi tambahan yang menyelesaikan array (opsional).

## Contoh (MongoDB Shell)
<a name="setUnion-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$setUnion` operator untuk menggabungkan elemen unik dari dua bidang array dalam koleksi.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      allInterests: { $setUnion: ["$hobbies", "$skills"] }
    }
  }
]);
```

**Keluaran**

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

Dalam contoh ini, `$setUnion` operator digunakan untuk menggabungkan elemen unik dari bidang `hobbies` dan `skills` array untuk setiap dokumen pengguna. `allInterests`Bidang yang dihasilkan berisi penyatuan semua hobi dan keterampilan unik untuk setiap pengguna.

## Contoh kode
<a name="setUnion-code"></a>

Untuk melihat contoh kode untuk menggunakan `$setUnion` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

Di Amazon DocumentDB, `$skip` operator digunakan untuk mengimbangi titik awal hasil kueri, memungkinkan Anda untuk mengambil subset tertentu dari dokumen yang cocok. Ini sangat berguna dalam skenario pagination, di mana Anda ingin mengambil halaman hasil berikutnya.

**Parameter**
+ `skip`: Jumlah dokumen yang harus dilewati sebelum mengembalikan dokumen yang tersisa.

## Contoh (MongoDB Shell)
<a name="skip-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$skip` operator untuk mengambil halaman kedua hasil (dokumen 11-20) dari koleksi.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.collection.find({}, { "name": 1 })
             .skip(10)
             .limit(10);
```

**Keluaran**

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

## Contoh kode
<a name="skip-code"></a>

Untuk melihat contoh kode untuk menggunakan `$skip` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$slice` agregasi memungkinkan Anda mengembalikan subset array dengan melintasi array dari awal atau akhir array. Ini digunakan untuk menampilkan sejumlah item terbatas dari bidang array, seperti item N atas atau bawah.

**Parameter**
+ `array`: Bidang array yang akan diiris.
+ `n`: Sebuah integer yang menentukan jumlah elemen untuk kembali. Nilai positif dimulai dari awal array, sedangkan nilai negatif dimulai dari akhir array.

## Contoh (MongoDB Shell)
<a name="slice-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$slice` untuk mengembalikan dua permen favorit pertama untuk setiap koki.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.sweets.aggregate([
  { $project: { _id: 0, name: 1, topTwoFavorites: { $slice: [ "$favorites", 2 ] } } }
]);
```

**Keluaran**

```
[
  { name: 'Alvin', topTwoFavorites: [ 'chocolate', 'cake' ] },
  { name: 'Tom', topTwoFavorites: [ 'donuts', 'pudding' ] },
  { name: 'Jessica', topTwoFavorites: [ 'fudge', 'smores' ] },
  { name: 'Rachel', topTwoFavorites: [ 'ice cream' ] }
]
```

Dalam contoh ini, `$slice` operator digunakan untuk mengekstrak dua elemen pertama dari `favorites` array untuk setiap dokumen.

## Contoh kode
<a name="slice-code"></a>

Untuk melihat contoh kode untuk menggunakan `$slice` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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`Operator digunakan untuk mengembalikan jumlah item dalam bidang array. Ini dapat digunakan untuk menentukan jumlah elemen dalam array yang disimpan dalam dokumen.

**Parameter**
+ `field`: Jalur bidang yang ukuran arry-nya ingin Anda kembalikan.

## Contoh (MongoDB Shell)
<a name="size-examples"></a>

Contoh ini menunjukkan cara menggunakan `$size` operator untuk mengembalikan jumlah tim yang diikuti setiap pengguna.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.profiles.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      "numberOfTeams": { $size: "$teams" }
    }
  }
])
```

**Keluaran**

```
[
  { name: 'John Doe', numberOfTeams: 3 },
  { name: 'Jane Smith', numberOfTeams: 2 },
  { name: 'Bob Johnson', numberOfTeams: 3 }
]
```

## Contoh kode
<a name="size-code"></a>

Untuk melihat contoh kode untuk menggunakan `$size` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Tahap `$sort` agregasi memesan dokumen dalam pipeline berdasarkan nilai bidang yang ditentukan. Dokumen disusun dalam urutan naik atau turun sesuai dengan kriteria pengurutan yang disediakan.

**Parameter**
+ `field`: Nama bidang untuk mengurutkan berdasarkan.
+ `order`: Gunakan `1` untuk urutan menaik atau `-1` untuk urutan menurun.

## Contoh (MongoDB Shell)
<a name="sort-examples"></a>

Contoh berikut menunjukkan penggunaan `$sort` panggung untuk memesan produk berdasarkan harga dalam urutan menurun.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.products.aggregate([
  { $sort: { price: -1 } }
]);
```

**Keluaran**

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

## Contoh kode
<a name="sort-code"></a>

Untuk melihat contoh kode untuk menggunakan tahap `$sort` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$split` agregasi di Amazon DocumentDB digunakan untuk membagi string menjadi array substring, berdasarkan pembatas tertentu. Ini dapat berguna untuk mengurai bidang string yang kompleks dan mengekstraksi komponen individual untuk diproses lebih lanjut.

**Parameter**
+ `string`: String yang akan dibagi.
+ `delimiter`: Karakter atau string yang digunakan untuk membagi string input.

## Contoh (MongoDB Shell)
<a name="split-examples"></a>

Dalam contoh ini, kita gunakan `$split` untuk memisahkan komponen bidang “Desk” ke dalam array, sehingga lebih mudah untuk memproses data.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

Output dari `$split` membuat array yang dapat digunakan dalam aplikasi untuk menampilkan informasi bagi karyawan.

## Contoh kode
<a name="split-code"></a>

Untuk melihat contoh kode untuk menggunakan `$split` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

Baru dari versi 4.0.

`$sqrt`Operator di Amazon DocumentDB digunakan untuk menghitung akar kuadrat dari suatu angka.

**Parameter**
+ `expression`: Argumen dapat berupa ekspresi yang valid selama diselesaikan menjadi angka non-negatif.

## Contoh (MongoDB Shell)
<a name="sqrt-examples"></a>

Contoh berikut menunjukkan penggunaan `$sqrt` operator untuk menghitung akar kuadrat dari angka.

**Buat dokumen sampel**

```
db.numbers.insertMany([
  { "_id": 1, "number": 16 },
  { "_id": 2, "number": 36 },
  { "_id": 3, "number": 64 }
]);
```

**Contoh kueri**

```
db.numbers.aggregate([
  { $project: {
    "_id": 1,
    "square_root": { $sqrt: "$number" }
  }}
]);
```

**Keluaran**

```
[
  { _id: 1, square_root: 4 },
  { _id: 2, square_root: 6 },
  { _id: 3, square_root: 8 }
]
```

## Contoh kode
<a name="sqrt-code"></a>

Untuk melihat contoh kode untuk menggunakan `$sqrt` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function 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>

`$strLenBytes`Operator di Amazon DocumentDB digunakan untuk menentukan panjang string dalam byte. Ini berguna ketika Anda perlu memahami ukuran penyimpanan bidang string, terutama ketika berhadapan dengan karakter Unicode yang mungkin menggunakan lebih dari satu byte per karakter.

**Parameter**
+ `expression`: Ekspresi string untuk menghitung panjang.

## Contoh (MongoDB Shell)
<a name="strLenBytes-examples"></a>

Contoh ini menunjukkan bagaimana menggunakan `$strLenBytes` operator untuk menghitung panjang bidang string dalam byte.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenBytes: "$Desk" }
    }
  }
])
```

**Keluaran**

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

Perhatikan bahwa panjang string “Düsseldorf-BVV-021" adalah 19 byte, yang berbeda dari jumlah titik kode (18) karena karakter Unicode “Ü” menempati 2 byte.

## Contoh kode
<a name="strLenBytes-code"></a>

Untuk melihat contoh kode untuk menggunakan `$strLenBytes` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$strLenCP`Operator di Amazon DocumentDB digunakan untuk menentukan panjang ekspresi string di titik kode (karakter Unicode). Ini berguna ketika Anda perlu mengetahui jumlah karakter dalam string, bukan jumlah byte.

**Parameter**
+ `expression`: Ekspresi string untuk mengembalikan panjang dalam poin kode.

## Contoh (MongoDB Shell)
<a name="strLenCP-examples"></a>

Contoh berikut menunjukkan penggunaan `$strLenCP` operator untuk menentukan panjang string dengan karakter Unicode.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenCP: "$Desk" }
    }
  }
])
```

**Keluaran**

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

Perhatikan perbedaan pengukuran panjang untuk string “Düsseldorf-BVV-021", yang berisi karakter Unicode (Ü). `$strLenCP`Operator menghitung jumlah karakter Unicode dengan benar, sedangkan `$strLenBytes` operator menghitung jumlah byte.

## Contoh kode
<a name="strLenCP-code"></a>

Untuk melihat contoh kode untuk menggunakan `$strLenCP` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Berikut adalah contoh penggunaan `$strLenCP` operator dalam aplikasi Node.js dengan driver MongoDB:

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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 ]

Berikut adalah contoh penggunaan `$strLenCP` operator dalam aplikasi Python dengan driver: PyMongo 

```
from pymongo import MongoClient

def example():
    client = 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>

`$strcasecmp`Operator di Amazon DocumentDB melakukan perbandingan case-insensitive antara dua string. Ia mengembalikan nilai integer yang menunjukkan perbandingan leksikografi dari dua string input, mengabaikan perbedaan kasus.

**Parameter**
+ `string1`: String pertama untuk membandingkan.
+ `string2`: String kedua untuk membandingkan.

## Contoh (MongoDB Shell)
<a name="strcasecmp-examples"></a>

Contoh ini menunjukkan cara menggunakan `$strcasecmp` operator untuk membandingkan string lokasi meja dalam `people` koleksi, mengabaikan perbedaan kasus.

**Buat dokumen sampel**

```
db.people.insertMany([
  { "_id": 1, "Desk": "mke233-wi" },
  { "_id": 2, "Desk": "MKE233-WI" },
  { "_id": 3, "Desk": "mke233-wi" }
]);
```

**Contoh kueri**

```
db.people.aggregate([
  {
    $project: {
      item: 1,
      compare: { $strcasecmp: ["$Desk", "mke233-wi"] }
    }
  }
]);
```

**Keluaran**

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

Output menunjukkan bahwa perbandingan antara `&quot;Desk&quot;` bidang dan string `&quot;mke233-wi&quot;` kembali `0` untuk ketiga dokumen, menunjukkan bahwa string sama ketika kasus diabaikan.

## Contoh kode
<a name="strcasecmp-code"></a>

Untuk melihat contoh kode untuk menggunakan `$strcasecmp` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$substr`Operator di Amazon DocumentDB digunakan untuk mengekstrak substring dari string yang diberikan. Ini sangat berguna ketika Anda perlu mendefinisikan substring berdasarkan berbagai karakter, bukan rentang byte. Ini sangat penting ketika berhadapan dengan string Unicode, di mana jumlah byte yang digunakan untuk mewakili karakter dapat bervariasi.

**Parameter**
+ `string`: String input dari mana untuk mengekstrak substring.
+ `start`: Posisi awal (berbasis nol) dari substring yang akan diekstraksi. Bisa berupa ekspresi integer non-negatif.
+ `length`: Jumlah karakter dalam substring yang diekstraksi. Bisa berupa ekspresi integer non-negatif.

## Contoh (MongoDB Shell)
<a name="substr-examples"></a>

Dalam contoh ini, kami akan mendemonstrasikan penggunaan `$substr` untuk mengekstrak singkatan negara dari lokasi meja karyawan.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substr: ["$Desk", 12, 3] }
    }
  }
])
```

**Keluaran**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

## Contoh kode
<a name="substr-code"></a>

Untuk melihat contoh kode untuk menggunakan `$substr` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<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>

`$substrBytes`Operator di Amazon DocumentDB digunakan untuk mengekstrak substring dari string berdasarkan rentang byte tertentu. Operator ini berguna ketika Anda perlu mengekstrak substring dari string dan jumlah byte yang diperlukan untuk mewakili setiap karakter dalam string adalah penting.

Tidak seperti`$substrCP`, yang beroperasi pada jumlah titik kode Unicode, `$substrBytes` beroperasi pada jumlah byte yang diperlukan untuk mewakili karakter dalam string. Ini bisa sangat berguna ketika bekerja dengan string yang berisi karakter non-ASCII, karena karakter ini mungkin memerlukan lebih dari satu byte untuk mewakili.

\$1Catatan: \$1 `$substr` telah usang sejak versi 3.4. `$substr`sekarang alias untuk`$substrBytes`.

**Parameter**
+ `string`: String input dari mana substring akan diekstraksi.
+ `startByte`: Posisi byte awal berbasis nol dari substring yang akan diekstraksi. Nilai negatif dapat digunakan untuk menentukan posisi dari akhir string.
+ `length`: Jumlah byte dalam substring yang akan diekstraksi.

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

Dalam contoh ini, kita akan menggunakan `$substrBytes` untuk mengekstrak substring dari string yang berisi karakter non-ASCII.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrBytes: [ "$Desk", 12, 3] }
    }
  }
])
```

**Keluaran**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

Dalam contoh ini, kita gunakan `$substrBytes` untuk mengekstrak substring 3-byte mulai dari byte ke-12 bidang. `Desk` Ini memungkinkan kita untuk mengekstrak singkatan status 2 karakter, meskipun string mungkin berisi karakter non-ASCII.

## Contoh kode
<a name="substrBytes-code"></a>

Untuk melihat contoh kode untuk menggunakan `$substrBytes` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

`$substrCP`Operator di Amazon DocumentDB digunakan untuk mengekstrak substring dari string, di mana substring ditentukan sebagai rentang titik kode UTF-8 (CP). Operator ini sangat berguna ketika bekerja dengan string Unicode, karena memungkinkan Anda untuk mengekstrak substring tanpa harus khawatir tentang representasi byte yang mendasari karakter.

Berbeda dengan `$substrBytes` operator, yang beroperasi pada posisi byte, `$substrCP` operator bekerja dengan posisi titik kode. Ini membuatnya lebih mudah untuk bekerja dengan string yang berisi karakter non-ASCII, karena jumlah titik kode mungkin tidak cocok dengan jumlah byte atau karakter.

**Parameter**
+ `string`: String input dari mana untuk mengekstrak substring.
+ `start`: Posisi titik kode awal (berbasis nol) dari mana untuk mengekstrak substring.
+ `length`: Jumlah poin kode untuk diekstrak.

## Contoh (MongoDB Shell)
<a name="substrCP-examples"></a>

Dalam contoh ini, kita akan menggunakan `$substrCP` operator untuk mengekstrak singkatan status dari string yang berisi lokasi meja karyawan.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrCP: ["$Desk", 25, 2] }
    }
  }
]);
```

**Keluaran**

```
{ "_id" : 1, "state" : "MN" }
{ "_id" : 2, "state" : "LA" }
{ "_id" : 3, "state" : "CA" }
```

Dalam contoh ini, kita tahu bahwa singkatan status dimulai pada titik kode ke-25 di `Desk` bidang dan panjangnya 2 poin kode. Dengan menggunakan `$substrCP` operator, kita dapat mengekstrak singkatan status tanpa harus khawatir tentang representasi byte yang mendasarinya dari string.

## Contoh kode
<a name="substrCP-code"></a>

Untuk melihat contoh kode untuk menggunakan `$substrCP` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Dalam contoh Node.js dan Python, kami menggunakan `$substrCP` operator untuk mengekstrak singkatan status dari `Desk` bidang, mirip dengan contoh MongoDB Shell.

------

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

`$subtract`Operator di Amazon DocumentDB digunakan untuk mengurangi nilai. Ini dapat digunakan untuk mengurangi tanggal, angka, atau kombinasi keduanya. Operator ini berguna untuk menghitung selisih antara dua tanggal atau mengurangi nilai dari angka.

**Parameter**
+ `expression1`: Nilai pertama yang akan dikurangi.
+ `expression2`: Nilai kedua yang akan dikurangi dari. `<expression1>`

## Contoh (MongoDB Shell)
<a name="subtract-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$subtract` operator untuk menghitung perbedaan antara dua tanggal.

**Buat dokumen sampel**

```
db.dates.insert([
  {
  "_id": 1,
  "startDate": ISODate("2023-01-01T00:00:00Z"),
  "endDate": ISODate("2023-01-05T12:00:00Z")
  }
]);
```

**Contoh kueri**

```
db.dates.aggregate([
  {
    $project: {
      _id: 1,
      durationDays: {
        $divide: [
          { $subtract: ["$endDate", "$startDate"] },
          1000 * 60 * 60 * 24  // milliseconds in a day
        ]
      }
    }
  }
]);
```

**Keluaran**

```
[ { _id: 1, durationDays: 4.5 } ]
```

Dalam contoh ini, `$subtract` operator digunakan untuk menghitung perbedaan antara `$endDate` dan `$startDate` dalam hari.

## Contoh kode
<a name="subtract-code"></a>

Untuk melihat contoh kode untuk menggunakan `$subtract` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function 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>

`$sum`Operator di Amazon DocumentDB mengembalikan jumlah ekspresi yang ditentukan untuk setiap dokumen dalam grup. Ini adalah operator akumulator grup yang biasanya digunakan dalam tahap \$1group dari pipa agregasi untuk melakukan perhitungan penjumlahan.

**Parameter**
+ `expression`: Ekspresi numerik untuk jumlah. Ini bisa berupa jalur lapangan, ekspresi, atau konstanta.

## Contoh (MongoDB Shell)
<a name="sum-examples"></a>

Contoh berikut menunjukkan penggunaan `$sum` operator untuk menghitung total penjualan untuk setiap produk.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.sales.aggregate([
  { $group: {
      _id: "$product",
      totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } }
    }}
]);
```

**Keluaran**

```
[
  { "_id": "abc", "totalSales": 50 },
  { "_id": "xyz", "totalSales": 120 }
]
```

## Contoh kode
<a name="sum-code"></a>

Untuk melihat contoh kode untuk menggunakan `$sum` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Baru dari versi 4.0.

Tidak didukung oleh cluster elastis.

`$switch`Operator adalah operator ekspresi bersyarat di Amazon DocumentDB yang memungkinkan Anda mengevaluasi daftar ekspresi kasus dan mengembalikan nilai kasus pertama yang mengevaluasi ke true, atau nilai default jika tidak ada ekspresi kasus yang benar.

**Parameter**
+ `branches`: Sebuah array dokumen, yang masing-masing memiliki bidang kasus yang berisi ekspresi boolean untuk mengevaluasi, dan kemudian bidang yang berisi nilai untuk kembali jika ekspresi kasus benar.
+ `default`: (opsional) Nilai yang akan dikembalikan jika tidak ada ekspresi kasus yang benar.

## Contoh (MongoDB Shell)
<a name="switch-examples"></a>

Contoh berikut menunjukkan penggunaan `$switch` operator untuk menentukan biaya pengiriman pesanan berdasarkan total pesanan.

**Buat dokumen sampel**

```
db.orders.insertMany([
  { _id: 1, total: 50 },
  { _id: 2, total: 150 },
  { _id: 3, total: 250 }
]);
```

**Contoh kueri**

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

**Keluaran**

```
[
  {
    "_id": 1,
    "total": 50,
    "shippingCost": 5
  },
  {
    "_id": 2,
    "total": 150,
    "shippingCost": 10
  },
  {
    "_id": 3,
    "total": 250,
    "shippingCost": 15
  }
]
```

## Contoh kode
<a name="switch-code"></a>

Untuk melihat contoh kode untuk menggunakan `$switch` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$toBool`Operator di Amazon DocumentDB mengonversi ekspresi ke nilai boolean.

**Parameter**
+ `expression`: Ekspresi yang akan dikonversi ke nilai boolean.

**Catatan**: Setiap string dikonversi ke`true`.

## Contoh (MongoDB Shell)
<a name="toBool-examples"></a>

Contoh berikut menunjukkan penggunaan `$toBool` operator untuk menormalkan nilai status perangkat dari tipe data yang berbeda.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.deviceStates.aggregate([
  {
    $project: {
      _id: 1,
      deviceId: 1,
      isActive: { $toBool: "$status" }
    }
  }
]);
```

**Keluaran**

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

## Contoh kode
<a name="toBool-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toBool` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Baru dari versi 4.0

Operator `$toDate` agregasi di Amazon DocumentDB digunakan untuk mengonversi string tanggal atau tanggal dan waktu ke jenis Tanggal BSON. Ini adalah operasi terbalik dari `$dateToString` operator.

**Parameter**
+ `dateString`: Sebuah representasi string dari tanggal atau tanggal dan waktu yang akan dikonversi ke jenis Tanggal BSON.
+ `format`: (opsional) Sebuah string yang menentukan format. `dateString` Jika tidak disediakan, operator akan mencoba mengurai `dateString` dalam berbagai format tanggal dan waktu standar.
+ `timezone`: (opsional) String yang mewakili zona waktu yang akan digunakan untuk konversi. Jika tidak disediakan, zona waktu lokal digunakan.

## Contoh (MongoDB Shell)
<a name="toDate-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$toDate` operator untuk mengkonversi string tanggal ke tipe BSON Date.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.events.aggregate([
  {
    $project: {
      eventName: 1,
      eventTimeDate: { $toDate: "$eventTime" }
    }
  }
]);
```

**Keluaran**

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

## Contoh kode
<a name="toDate-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toDate` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0

`$toDecimal`Operator di Amazon DocumentDB digunakan untuk mengonversi nilai ke tipe data Decimal128. Ini berguna ketika Anda perlu melakukan aritmatika desimal yang tepat atau menangani nilai desimal besar yang tidak dapat direpresentasikan secara akurat menggunakan tipe data ganda.

**Parameter**
+ `expression`: Ekspresi untuk mengkonversi ke tipe data Decimal128.

## Contoh (MongoDB Shell)
<a name="toDecimal-examples"></a>

Contoh ini menunjukkan bagaimana menggunakan `$toDecimal` operator untuk mengkonversi nilai string ke tipe data Decimal128.

**Buat dokumen sampel**

```
db.numbers.insertOne({ _id: 1, value: "3.14" });
db.numbers.insertOne({ _id: 2, value: "2.71" });
```

**Contoh kueri**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    decimalValue: { $toDecimal: "$value" }
  }}
])
```

**Keluaran**

```
[
  { "_id" : 1, "decimalValue" : Decimal128("3.14") },
  { "_id" : 2, "decimalValue" : Decimal128("2.71") }
]
```

## Contoh kode
<a name="toDecimal-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toDecimal` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0

`$toDouble`Operator di Amazon DocumentDB digunakan untuk mengonversi nilai menjadi nomor floating-point 64-bit presisi ganda. Ini dapat berguna ketika Anda perlu melakukan operasi aritmatika pada nilai-nilai yang awalnya tidak dalam format numerik.

**Parameter**

`&lt;expression&gt;`: Ekspresi untuk mengkonversi ke nilai ganda. Ini bisa berupa ekspresi valid yang menyelesaikan nilai numerik, string, atau boolean.

## Contoh (MongoDB Shell)
<a name="toDouble-examples"></a>

Contoh ini menunjukkan bagaimana menggunakan `$toDouble` operator untuk mengkonversi nilai string ke nilai numerik untuk tujuan melakukan perhitungan matematis.

**Buat dokumen sampel**

```
db.numbers.insertMany([
  { _id: 1, value: "10.5" },
  { _id: 2, value: "20.25" },
  { _id: 3, value: "7" }
])
```

**Contoh kueri**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      value: 1,
      double_value: { $toDouble: "$value" },
      double_plus_five: { $add: [{ $toDouble: "$value" }, 5] }
    }
  }
])
```

**Keluaran**

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

## Contoh kode
<a name="toDouble-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toDouble` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0

`$toInt`Operator di Amazon DocumentDB digunakan untuk mengonversi nilai input ke tipe data integer. Operator ini berguna ketika Anda perlu memastikan bahwa bidang atau ekspresi direpresentasikan sebagai bilangan bulat, yang dapat menjadi penting untuk operasi tertentu atau tugas pemrosesan data.

**Parameter**
+ `expression`: Ekspresi yang akan dikonversi ke integer.

## Contoh (MongoDB Shell)
<a name="toInt-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$toInt` operator untuk mengkonversi nilai string ke integer.

**Buat dokumen sampel**

```
db.numbers.insertMany([
  { "name": "one", "value": "1" },
  { "name": "hundred", "value": "100" }
]);
```

**Contoh kueri**

```
db.numbers.aggregate([
  { $project: {
    "_id": 0,
    "name": 1,
    "intValue": { $toInt: "$value" }
  }}
]);
```

**Keluaran**

```
{ "name": "one", "intValue": 1 }
{ "name": "hundred", "intValue": 100 }
```

## Contoh kode
<a name="toInt-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toInt` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0

`$toLong`Operator di Amazon DocumentDB digunakan untuk mengonversi nilai menjadi tipe data integer (panjang) 64-bit. Ini dapat berguna ketika Anda perlu melakukan operasi aritmatika atau perbandingan pada nilai numerik yang dapat disimpan sebagai string atau tipe data lainnya.

**Parameter**
+ `expression`: Ekspresi untuk mengkonversi ke integer 64-bit.

## Contoh (MongoDB Shell)
<a name="toLong-examples"></a>

Contoh ini menunjukkan bagaimana menggunakan `$toLong` operator untuk mengkonversi nilai string ke integer 64-bit.

**Buat dokumen sampel**

```
db.numbers.insertMany([
  { _id: 1, value: "42" },
  { _id: 3, value: "9223372036854775807" }
]);
```

**Contoh kueri**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      longValue: { $toLong: "$value" }
    }
  }
])
```

**Keluaran**

```
[
  { "_id" : 1, "longValue" : 42 },
  { "_id" : 3, "longValue" : 9223372036854775807 }
]
```

## Contoh kode
<a name="toLong-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toLong` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

`$toLower`Operator di Amazon DocumentDB digunakan untuk mengonversi string ke huruf kecil.

**Parameter**
+ `expression`: Ekspresi string untuk mengkonversi ke huruf kecil.

## Contoh (MongoDB Shell)
<a name="toLower-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$toLower` operator untuk mengkonversi `Desk` bidang ke huruf kecil.

**Buat dokumen sampel**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" }
]);
```

**Contoh kueri**

```
db.locations.aggregate([
  { $project: { item: { $toLower: "$Desk" } } }
]);
```

**Keluaran**

```
{ "_id" : 1, "item" : "düsseldorf-bvv-021" }
{ "_id" : 2, "item" : "munich-hgg-32a" }
```

## Contoh kode
<a name="toLower-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toLower` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Baru dari versi 4.0

`$toObjectId`Operator di Amazon DocumentDB digunakan untuk mengonversi representasi string dari tipe data aktual ke tipe ObjectId data ObjectId aktual. Hal ini dapat berguna ketika bekerja dengan data yang telah disimpan sebagai representasi string ObjectIds, karena memungkinkan Anda untuk melakukan operasi yang memerlukan tipe ObjectId data.

**Parameter**
+ `expression`: Ekspresi string yang mewakili valid ObjectId.

## Contoh (MongoDB Shell)
<a name="toObjectId-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$toObjectId` operator untuk mengkonversi representasi string dari tipe ObjectId data. ObjectId 

**Buat dokumen sampel**

```
db.employees.insertMany([
  { _id: 1, empId:"64e5f8886218c620cf0e8f8a", name: "Carol Smith", employeeId: "c720a" },
  { _id: 2, empId:"64e5f94e6218c620cf0e8f8c", name: "Bill Taylor", employeeId: "c721a" }
]);
```

**Contoh kueri**

```
db.employees.aggregate([
  { $project: {
    "empIdAsObjectId": {$toObjectId: "$empId"}}
  }
]);
```

**Keluaran**

```
[
  { _id: 1, empIdAsObjectId: ObjectId('64e5f8886218c620cf0e8f8a') },
  { _id: 2, empIdAsObjectId: ObjectId('64e5f94e6218c620cf0e8f8c') }
]
```

## Contoh kode
<a name="toObjectId-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toObjectId` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0

`$toString`Operator di Amazon DocumentDB digunakan untuk mengonversi nilai jenis apa pun (kecuali null) menjadi representasi string. Ini dapat berguna ketika Anda perlu melakukan operasi string pada nilai-nilai yang awalnya tidak dalam format string.

**Parameter**
+ `expression`: Ekspresi untuk mengkonversi ke string.

## Contoh (MongoDB Shell)
<a name="toString-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$toString` operator untuk mengkonversi nilai numerik untuk string.

**Buat dokumen sampel**

```
db.numbers.insertMany([
  { "_id": 1, "value": 42 },
  { "_id": 2, "value": 3.14 }
]);
```

**Contoh kueri**

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

**Keluaran**

```
{ "_id": 1, "valueAsString": "42" }
{ "_id": 2, "valueAsString": "3.14" }
```

## Contoh kode
<a name="toString-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toString` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$toUpper`Operator di Amazon DocumentDB digunakan untuk mengonversi string ke huruf besar.

**Parameter**
+ `expression`: Ekspresi string untuk mengkonversi ke huruf besar.

## Contoh (MongoDB Shell)
<a name="toUpper-examples"></a>

Contoh berikut menunjukkan penggunaan `$toUpper` operator untuk mengkonversi `Desk` bidang ke huruf besar.

**Buat dokumen sampel**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "düsseldorf-bvv-021" },
  { "_id": 2, "Desk": "munich-hgg-32a" }
]);
```

**Contoh kueri**

```
db.locations.aggregate([
  { $project: { item: { $toUpper: "$Desk" } } }
]);
```

**Keluaran**

```
{ "_id" : 1, "item" : "DüSSELDORF-BVV-021" }
{ "_id" : 2, "item" : "MUNICH-HGG-32A" }
```

## Contoh kode
<a name="toUpper-code"></a>

Untuk melihat contoh kode untuk menggunakan `$toUpper` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 4.0

`$trim`Operator di Amazon DocumentDB digunakan untuk menghapus karakter spasi putih and/or terdepan dari string.

**Parameter**
+ `input`: Ekspresi string untuk memangkas.
+ `chars`: (opsional) Menentukan karakter untuk memangkas dari awal dan akhir input, defaultnya adalah spasi putih.

## Contoh (MongoDB Shell)
<a name="trim-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$trim` operator untuk menghapus spasi putih depan dan belakang dari string.

**Buat dokumen sampel**

```
db.people.insertMany([
  { "name": "   John Doe   " },
  { "name": "   Bob Johnson   " }
])
```

**Contoh kueri**

```
db.people.aggregate([
  { $project: {
    "name": { $trim: {input: "$name"}}
  }}
])
```

**Keluaran**

```
[
  { "name": "John Doe" },
  { "name": "Bob Johnson" }
]
```

## Contoh kode
<a name="trim-code"></a>

Untuk melihat contoh kode untuk menggunakan `$trim` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$type` agregasi mengembalikan tipe data BSON dari bidang tertentu. Ini berguna untuk mengidentifikasi tipe data nilai bidang selama operasi agregasi.

**Parameter**
+ `expression`: Bidang atau ekspresi yang tipenya akan dikembalikan.

## Contoh (MongoDB Shell)
<a name="type-aggregation-examples"></a>

Contoh berikut menunjukkan penggunaan `$type` operator untuk mengidentifikasi tipe data bidang harga untuk setiap produk.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      price: 1,
      priceType: { $type: "$price" }
    }
  }
]);
```

**Keluaran**

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

## Contoh kode
<a name="type-aggregation-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$type` agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Baru dari versi 8.0

Tidak didukung oleh cluster elastis.

Tahap `$unset` agregasi di Amazon DocumentDB memungkinkan Anda menghapus bidang dari dokumen.

**Parameter**
+ `expression`: Nama bidang atau daftar beberapa nama bidang.

## Contoh (MongoDB Shell)
<a name="unset-stage-examples"></a>

Contoh berikut menunjukkan penggunaan tahap `$unset` agregasi untuk menghapus bidang. `price`

**Buat dokumen sampel**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**Contoh agregasi**

```
db.inventory.aggregate([
  {
    $unset: "price"
  }
])
```

**Keluaran**

```
[
  {
    _id: ObjectId('69248951d66dcae121d2950d'),
    item: 'pencil',
    quantity: 100
  },
  {
    _id: ObjectId('69248951d66dcae121d2950e'),
    item: 'pen',
    quantity: 204
  }
]
```

## Contoh kode
<a name="unset-stage-code"></a>

Untuk melihat contoh kode untuk menggunakan `$unset` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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`Operator digunakan untuk mendekonstruksi bidang array dari dokumen input untuk output dokumen untuk setiap elemen. Ini dapat berguna ketika Anda ingin melakukan operasi pada elemen individual dari array, seperti memfilter, menyortir, atau mengubah data.

**Parameter**
+ `path`: Jalur ke bidang array yang akan dilepas.
+ `includeArrayIndex`: (opsional) Menentukan nama bidang baru untuk menahan indeks elemen array.
+ `preserveNullAndEmptyArrays`: (opsional) Menentukan apakah operasi menyimpan dokumen asli ketika bidang array adalah null atau array kosong.

## Contoh (MongoDB Shell)
<a name="unwind-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$unwind` operator untuk mendekonstruksi bidang array dan melakukan operasi lebih lanjut pada elemen individu.

**Buat dokumen sampel**

```
db.people.insertMany([
  { _id: 1, name: "jon", hobbies: ["painting", "dancing", "singing"] },
  { _id: 2, name: "jane", hobbies: ["reading", "swimming"] },
  { _id: 3, name: "jack", hobbies: [] }
])
```

**Contoh kueri**

```
db.people.aggregate([
  { $unwind: "$hobbies" }
])
```

**Keluaran**

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

## Contoh kode
<a name="unwind-code"></a>

Untuk melihat contoh kode untuk menggunakan `$unwind` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Baru dari versi 8.0

Tidak didukung oleh cluster elastis.

`$vectorSearch`Operator di Amazon DocumentDB memungkinkan Anda melakukan pencarian vektor, metode yang digunakan dalam pembelajaran mesin untuk menemukan titik data serupa dengan membandingkan representasi vektornya menggunakan metrik jarak atau kesamaan. Kemampuan ini menggabungkan fleksibilitas dan kueri yang kaya dari database dokumen berbasis JSON dengan kekuatan pencarian vektor, memungkinkan Anda untuk membangun pembelajaran mesin dan kasus penggunaan AI generatif seperti pencarian semantik, rekomendasi produk, dan banyak lagi.

**Parameter**
+ `<exact>`(opsional): Bendera yang menentukan apakah akan menjalankan pencarian Exact Nearest Neighbor (ENN) atau Perkiraan Tetangga Terdekat (ANN). Nilai dapat menjadi salah satu dari berikut ini:
+ false - untuk menjalankan pencarian ANN
+ true - untuk menjalankan pencarian ENN

Jika dihilangkan atau disetel ke false, `numCandidates` diperlukan.

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

## Contoh (MongoDB Shell)
<a name="vectorSearch-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$vectorSearch` operator untuk menemukan deskripsi produk serupa berdasarkan representasi vektor mereka.

**Buat dokumen sampel**

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

**Buat indeks pencarian vektor**

```
db.runCommand(
    {
        createIndexes: "products",
        indexes: [{
            key: {
                "description_vector": "vector"
            },
            vectorOptions: {
                type: "hnsw",
                dimensions: 3,
                similarity: "cosine",
                m: 16,
                efConstruction: 64
            },
            name: "description_index"
        }]
    }
);
```

**Contoh kueri**

```
db.products.aggregate([
  { $vectorSearch: {
      index: "description_index",
      limit: 2,
      numCandidates: 10,
      path: "description_vector",
      queryVector: [0.1, 0.2, 0.3]
    }
  }
]);
```

**Keluaran**

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

## Contoh kode
<a name="vectorSearch-code"></a>

Untuk melihat contoh kode untuk menggunakan `$vectorSearch` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$week`Operator di Amazon DocumentDB mengembalikan nomor minggu tanggal (0-53) berdasarkan standar ISO 8601. Jumlah minggu dihitung berdasarkan tahun dan hari dalam seminggu, dengan Senin sebagai hari pertama dalam seminggu.

**Parameter**

Tidak ada

## Contoh (MongoDB Shell)
<a name="week-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$week` operator untuk mengambil nomor minggu dari tanggal tertentu.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

```
[
  { "_id": 1, "week": 1 },
  { "_id": 2, "week": 2 },
  { "_id": 3, "week": 53 }
]
```

## Contoh kode
<a name="week-code"></a>

Untuk melihat contoh kode untuk menggunakan `$week` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

`$year`Operator di Amazon DocumentDB mengekstrak komponen tahun dari tanggal atau stempel waktu.

**Parameter**
+ `expression`: Ekspresi tanggal atau stempel waktu untuk mengekstrak komponen tahun.

## Contoh (MongoDB Shell)
<a name="year-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$year` operator untuk mengekstrak komponen tahun dari bidang tanggal.

**Buat dokumen sampel**

```
db.events.insertMany([
  { "_id": 1, "date": ISODate("2023-04-15T00:00:00Z") },
  { "_id": 3, "date": ISODate("2021-12-31T00:00:00Z") }
]);
```

**Contoh kueri**

```
db.events.aggregate([
  { $project: { year: { $year: "$date" } } }
]);
```

**Keluaran**

```
[
  { "_id": 1, "year": 2023 },
  { "_id": 3, "year": 2021 }
]
```

## Contoh kode
<a name="year-code"></a>

Untuk melihat contoh kode untuk menggunakan `$year` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$zip`Operator di Amazon DocumentDB memungkinkan Anda untuk menggabungkan beberapa array ke dalam satu array tupel (pasangan kunci-nilai). Ini berguna ketika Anda perlu membuat dokumen atau objek baru dengan menggabungkan data dari berbagai sumber atau array dalam dokumen.

**Parameter**
+ `inputs`: Sebuah array ekspresi yang menyelesaikan array. Array ini akan digabungkan menjadi satu array tupel.
+ `useLongestLength`: (opsional) Jika`true`, array output akan memiliki panjang array input terpanjang, padding array yang lebih pendek dengan `null` nilai. Jika`false`, array output akan memiliki panjang array input terpendek.
+ `defaults`: (opsional) Sebuah array nilai default untuk digunakan untuk tupel jika array input yang sesuai lebih pendek dari array input terpanjang dan `useLongestLength` adalah. `true`

## Contoh (MongoDB Shell)
<a name="zip-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$zip` operator untuk menggabungkan dua array ke dalam array tunggal tupel.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.grades.aggregate([
  {
    $project: {
      "name": 1,
      "scoredClasses": {
        $zip: {
          inputs: ["$scores", "$classes"],
          useLongestLength: true,
          defaults: [null, null]
        }
      }
    }
  }
])
```

**Keluaran**

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

## Contoh kode
<a name="zip-code"></a>

Untuk melihat contoh kode untuk menggunakan `$zip` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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()
```

------

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

Bagian ini memberikan informasi rinci tentang operator geospasial yang didukung oleh 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>

`$geometry`Operator di Amazon DocumentDB digunakan untuk menentukan objek geometri GeoJSON sebagai bagian dari kueri geospasial. Operator ini digunakan bersama dengan operator kueri geospasial lainnya seperti `$geoWithin` dan `$geoIntersects` untuk melakukan kueri spasial pada data Anda.

Di Amazon DocumentDB, operator mendukung jenis `$geometry` geometri GeoJSON berikut:
+ Poin
+ LineString
+ Polygon
+ MultiPoint
+ MultiLineString
+ MultiPolygon
+ GeometryCollection

**Parameter**
+ `type`: Jenis objek geometri GeoJSON, misalnya,,, dll. `Point` `Polygon`
+ `coordinates`: Sebuah array koordinat yang mewakili geometri. Struktur array koordinat tergantung pada jenis geometri.

## Contoh (MongoDB Shell)
<a name="geometry-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$geometry` operator untuk melakukan `$geoIntersects` query di Amazon DocumentDB.

**Buat dokumen sampel**

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

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="geometry-code"></a>

Untuk melihat contoh kode untuk menggunakan `$geometry` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$geoIntersects`Operator di Amazon DocumentDB digunakan untuk menemukan dokumen yang data geospasialnya berpotongan dengan objek GeoJSON tertentu. Operator ini berguna untuk aplikasi yang memerlukan identifikasi dokumen berdasarkan hubungan spasialnya dengan bentuk geografis tertentu, seperti poligon atau multipoligon.

**Parameter**
+ `$geometry`: Sebuah objek GeoJSON yang mewakili bentuk untuk memeriksa persimpangan. Jenis objek GeoJSON yang didukung `Point` adalah`LineString`,,, `Polygon` dan. `MultiPolygon`

## Contoh (MongoDB Shell)
<a name="geoIntersects-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$geoIntersects` operator untuk menemukan nama negara untuk kumpulan koordinat tertentu di Amazon DocumentDB.

**Buat dokumen sampel**

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

**Contoh kueri**

```
var location = [-73.965355, 40.782865];

db.states.find({
  "loc": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Point",
        "coordinates": location
      }
    }
  }
}, {
  "name": 1
});
```

**Keluaran**

```
{ "_id" : ObjectId("536b0a143004b15885c91a2c"), "name" : "New York" }
```

## Contoh kode
<a name="geoIntersects-code"></a>

Untuk melihat contoh kode untuk menggunakan `$geoIntersects` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$geoWithin`Operator di Amazon DocumentDB digunakan untuk menemukan dokumen yang data lokasinya (direpresentasikan sebagai objek GeoJSON) sepenuhnya terkandung dalam bentuk tertentu, seperti poligon atau multipoligon. Ini berguna untuk menanyakan objek yang terletak di dalam wilayah geografis tertentu.

**Parameter**
+ `$geometry`: Sebuah objek GeoJSON yang mewakili bentuk untuk query terhadap.

## Contoh (MongoDB Shell)
<a name="geoWithin-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$geoWithin` operator untuk menemukan semua bandara yang terletak di negara bagian New York.

**Buat dokumen sampel**

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

**Contoh kueri**

```
var state = db.states.findOne({"name": "New York"});

db.airports.find({
    "loc": {
        "$geoWithin": {
            "$geometry": state.loc
        }
    }
}, {
    "name": 1,
    "type": 1,
    "code": 1,
    "_id": 0
});
```

**Keluaran**

```
[
  {
    "name": "John F. Kennedy International Airport",
    "type": "airport",
    "code": "JFK"
  },
  {
    "name": "LaGuardia Airport",
    "type": "airport",
    "code": "LGA"
  }
]
```

## Contoh kode
<a name="geoWithin-code"></a>

Untuk melihat contoh kode untuk menggunakan `$geoWithin` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$maxDistance`Operator di Amazon DocumentDB digunakan untuk menentukan jarak maksimum (dalam meter) dari titik GeoJSON di mana dokumen harus berada di dalamnya untuk dimasukkan dalam hasil kueri. Operator ini digunakan bersama dengan `$nearSphere` operator untuk melakukan kueri geospasial.

**Parameter**
+ `$maxDistance`: Jarak maksimum (dalam meter) dari titik referensi di mana dokumen harus berada di dalamnya untuk dimasukkan dalam hasil kueri.

## Contoh (MongoDB Shell)
<a name="maxDistance-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$maxDistance` operator di Amazon DocumentDB untuk menemukan semua ibu kota negara bagian dalam jarak 100 kilometer dari Boston.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.capitals.find(
  {
    location: {
      $nearSphere: {
        $geometry: { type: "Point", coordinates: [-71.0589, 42.3601] },
        $maxDistance: 100000
      }
    }
  },
  { state: 1, city: 1, _id: 0 }
);
```

**Keluaran**

```
[
  { "state": "Rhode Island", "city": "Providence" },
  { "state": "New Hampshire", "city": "Concord" }
]
```

## Contoh kode
<a name="maxDistance-code"></a>

Untuk melihat contoh kode untuk menggunakan `$maxDistance` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`adalah operator find yang digunakan bersama dengan `$nearSphere` atau `$geoNear` untuk memfilter dokumen yang setidaknya pada jarak minimum yang ditentukan dari titik pusat. Operator ini didukung di Amazon DocumentDB dan fungsinya mirip dengan mitranya di MongoDB.

**Parameter**
+ `$minDistance`: Jarak minimum (dalam meter) dari titik pusat untuk memasukkan dokumen dalam hasil.

## Contoh (MongoDB Shell)
<a name="minDistance-examples"></a>

Dalam contoh ini, kita akan menemukan semua restoran dalam radius 2 kilometer dari lokasi tertentu di Seattle, Washington.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.usarestaurants.find({
  "location": {
    "$nearSphere": {
      "$geometry": {
        "type": "Point",
        "coordinates": [-122.3516, 47.6156]
      },
      "$minDistance": 1,
      "$maxDistance": 2000
    }
  }
}, {
  "name": 1
});
```

**Keluaran**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## Contoh kode
<a name="minDistance-code"></a>

Untuk melihat contoh kode untuk menggunakan `$minDistance` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$near`Operator di Amazon DocumentDB digunakan untuk menemukan dokumen yang secara geografis dekat titik tertentu. Ia mengembalikan dokumen yang dipesan berdasarkan jarak, dengan dokumen terdekat terlebih dahulu. Operator ini memerlukan indeks geospasial 2dsphere dan berguna untuk kueri kedekatan pada data lokasi.

**Parameter**
+ `$geometry`: Sebuah objek GeoJSON Point yang mendefinisikan titik pusat untuk query dekat.
+ `$maxDistance`: (opsional) Jarak maksimum dalam meter dari titik yang ditentukan bahwa dokumen dapat untuk mencocokkan kueri.
+ `$minDistance`: (opsional) Jarak minimum dalam meter dari titik yang ditentukan bahwa dokumen dapat untuk mencocokkan kueri.

**Persyaratan Indeks**
+ `2dsphere index`: Diperlukan untuk kueri geospasial pada data GeoJSON Point.

## Contoh (MongoDB Shell)
<a name="near-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$near` operator untuk menemukan restoran terdekat ke lokasi tertentu di Seattle, Washington.

**Buat dokumen sampel**

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

**Buat indeks 2dsphere**

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

**Contoh kueri dengan GeoJSON Point**

```
db.usarestaurants.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $maxDistance: 100,
      $minDistance: 10
    }
  }
});
```

**Keluaran**

```
{
  "_id" : ObjectId("69031ec9ea1c2922a1ce5f4a"),
  "name" : "Noodle House",
  "city" : "Seattle",
  "state" : "Washington",
  "rating" : 4.8,
  "location" : {
    "type" : "Point",
    "coordinates" : [ -122.3517, 47.6159 ]
  }
}
```

## Contoh kode
<a name="near-code"></a>

Untuk melihat contoh kode untuk menggunakan `$near` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$nearSphere`Operator di Amazon DocumentDB digunakan untuk menemukan dokumen yang berada dalam jarak tertentu dari titik geospasial. Operator ini sangat berguna untuk kueri geo-spasial, seperti menemukan semua restoran dalam radius tertentu dari lokasi tertentu.

**Parameter**
+ `$geometry`: Sebuah objek GeoJSON yang mewakili titik referensi. Harus menjadi `Point` objek dengan `type` dan `coordinates` bidang.
+ `$minDistance`: (opsional) Jarak minimum (dalam meter) dari titik referensi yang harus dimiliki dokumen.
+ `$maxDistance`: (opsional) Jarak maksimum (dalam meter) dari titik referensi yang harus dimiliki dokumen.

## Contoh (MongoDB Shell)
<a name="nearSphere-examples"></a>

Dalam contoh ini, kita akan menemukan semua restoran dalam jarak 2 kilometer (2000 meter) dari lokasi tertentu di Seattle, WA.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.usarestaurants.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $minDistance: 1,
      $maxDistance: 2000
    }
  }
}, {
  name: 1
});
```

**Keluaran**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## Contoh kode
<a name="nearSphere-code"></a>

Untuk melihat contoh kode untuk menggunakan `$nearSphere` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------

# Operator kueri dan proyeksi
<a name="mongo-apis-query-projection-operators"></a>

Bagian ini memberikan informasi terperinci tentang operator kueri dan proyeksi yang didukung oleh Amazon DocumentDB.

**Topics**
+ [\$1](dollar-projection.md)
+ [\$1 semua](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>

Operator `$` proyeksi membatasi isi bidang array untuk mengembalikan hanya elemen pertama yang cocok dengan kondisi kueri. Hal ini digunakan untuk memproyeksikan elemen array pencocokan tunggal.

**Parameter**
+ `field.$`: Bidang array dengan operator posisi untuk memproyeksikan elemen pencocokan pertama.

## Contoh (MongoDB Shell)
<a name="dollar-projection-examples"></a>

Contoh berikut menunjukkan menggunakan operator `$` proyeksi untuk mengembalikan hanya elemen array yang cocok.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.students.find(
  { grades: { $gte: 90 } },
  { name: 1, "grades.$": 1 }
);
```

**Keluaran**

```
{ "_id" : 1, "name" : "Alice", "grades" : [ 92 ] }
{ "_id" : 2, "name" : "Bob", "grades" : [ 92 ] }
{ "_id" : 3, "name" : "Charlie", "grades" : [ 95 ] }
```

Dalam contoh ini, hanya nilai satu yang lebih besar dari atau sama dengan 90 yang dikembalikan untuk setiap siswa.

## Contoh kode
<a name="dollar-projection-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$` proyeksi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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()
```

------

# \$1 semua
<a name="all"></a>

`$all`Operator di Amazon DocumentDB digunakan untuk mencocokkan dokumen di mana nilai bidang adalah array dan berisi semua elemen yang ditentukan, terlepas dari urutan elemen dalam array.

**Parameter**
+ `field`: Nama bidang yang akan diperiksa.
+ `[value1, value2, ...]`: Daftar nilai yang cocok dalam array.

 

**Menggunakan `$elemMatch` dalam `$all` ekspresi**

Lihat [Menggunakan `$elemMatch` dalam `$all` ekspresi](functional-differences.md#functional-differences.elemMatch) batasan mengenai penggunaan `$elemMatch` operator dalam `$all` ekspresi.

 

**Dolar (\$1) dalam nama bidang**

Lihat [Dolar (\$1) dan titik (.) dalam nama bidang](functional-differences.md#functional-differences-dollardot) batasan terkait kueri bidang `$` awalan `$all` di objek bersarang.

## Contoh (MongoDB Shell)
<a name="all-examples"></a>

Contoh berikut menunjukkan penggunaan `$all` operator untuk mengambil dokumen di mana bidang “Warna” adalah array yang berisi “Merah” dan “Biru”.

**Buat dokumen sampel**

```
db.example.insertMany([
  { "Item": "Pen", "Colors": ["Red", "Blue", "Green"] },
  { "Item": "Notebook", "Colors": ["Blue", "White"] },
  { "Item": "Poster Paint", "Colors": ["Red", "Yellow", "White"] }
])
```

**Contoh kueri**

```
db.example.find({ "Colors": { $all: ["Red", "Blue"] } }).pretty()
```

**Keluaran**

```
{
  "_id" : ObjectId("6137d6c5b3a1d35e0b6ee6ad"),
  "Item" : "Pen",
  "Colors" : [ 
          "Red", 
          "Blue", 
          "Green" 
  ]
}
```

## Contoh kode
<a name="all-code"></a>

Untuk melihat contoh kode untuk menggunakan `$all` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$and`Operator di Amazon DocumentDB digunakan untuk menggabungkan beberapa ekspresi dan mengevaluasinya sebagai satu kondisi. Ia kembali `true` jika semua ekspresi yang disediakan mengevaluasi`true`, dan `false` sebaliknya. Operator ini berguna untuk menerapkan beberapa kriteria ke kueri.

**Parameter**
+ `expression1`: Ekspresi wajib yang mengevaluasi nilai boolean.
+ `expression2`: Ekspresi wajib yang mengevaluasi nilai boolean.
+ `...`: Ekspresi tambahan yang diperlukan yang mengevaluasi nilai boolean.

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

Contoh berikut menunjukkan penggunaan `$and` operator untuk menemukan semua dokumen dalam koleksi “pengguna” di mana bidang “usia” lebih besar dari 18 dan bidang “status” adalah “aktif”.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.users.find({
  $and: [
    { age: { $gt: 18 } },
    { status: "active" }
  ]
});
```

**Keluaran**

```
[
  { "_id" : ObjectId("614e3c4b63f5892e7c4e2345"), "name" : "John", "age" : 25, "status" : "active" },
  { "_id" : ObjectId("614e3c4b63f5892e7c4e2347"), "name" : "Alice", "age" : 22, "status" : "active" }
]
```

## Contoh kode
<a name="and-code"></a>

Untuk melihat contoh kode untuk menggunakan `$and` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$bitsAllClear`Operator di Amazon DocumentDB digunakan untuk mencocokkan dokumen di mana semua bit yang ditentukan dalam bidang dihapus (diatur ke 0). Operator ini dapat berguna untuk melakukan operasi bitwise pada data yang disimpan.

**Parameter**
+ `field`: Bidang untuk memeriksa bit tertentu yang dihapus.
+ `value`: Bitmask numerik yang menentukan bit mana yang harus diperiksa, atau daftar posisi bit yang akan diperiksa. Bitmask numerik dapat berupa biner (0b...), desimal, heksadesimal (0x...), oktal (0o...), atau biner (). BinData Dalam daftar posisi bit, posisi bit yang paling tidak signifikan adalah 0.

## Contoh (MongoDB Shell)
<a name="bitsAllClear-examples"></a>

Contoh berikut menunjukkan penggunaan `$bitsAllClear` operator di Amazon DocumentDB.

**Buat dokumen sampel**

```
db.collection.insertMany([
  { _id: 1, bits: 0b1010 },
  { _id: 2, bits: 0b1100 },
  { _id: 3, bits: 0b0101 }
]);
```

**Contoh kueri**

```
db.collection.find({
  bits: { $bitsAllClear: 0b0011 }
})
```

**Keluaran**

```
{ "_id" : 2, "bits" : 12 }
```

Kueri memeriksa apakah semua bit yang ditentukan oleh bitmask `0b0011` (dua bit yang paling tidak signifikan) dihapus di `bits` lapangan. Dokumen dengan `_id` 2 memenuhi kondisi ini, karena `bits` bidangnya memiliki bit-bit yang dihapus.

## Contoh kode
<a name="bitsAllClear-code"></a>

Untuk melihat contoh kode untuk menggunakan `$bitsAllClear` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$bitsAllSet`Operator di Amazon DocumentDB digunakan untuk menanyakan dokumen di mana sekumpulan bit tertentu diatur ke 1 di bidang. Operator ini memungkinkan Anda untuk melakukan operasi bitwise pada nilai bidang dan dapat berguna ketika Anda perlu memeriksa status masing-masing bit dalam nilai numerik.

**Parameter**
+ `field`: Nama bidang numerik untuk melakukan operasi bitwise pada.
+ `value`: Bitmask numerik yang menentukan bit mana yang harus diperiksa, atau daftar posisi bit yang akan diperiksa. Bitmask numerik dapat berupa biner (0b...), desimal, heksadesimal (0x...), oktal (0o...), atau biner (). BinData Dalam daftar posisi bit, posisi bit yang paling tidak signifikan adalah 0.

## Contoh (MongoDB Shell)
<a name="bitsAllSet-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$bitsAllSet` operator untuk menemukan dokumen di mana `flags` bidang memiliki semua bit set yang ditentukan oleh bitmask.

**Buat dokumen sampel**

```
db.collection.insert([
  { _id: 1, flags: 0b1010 },
  { _id: 2, flags: 0b1100 },
  { _id: 3, flags: 0b1110 }
])
```

**Contoh kueri**

```
db.collection.find({ flags: { $bitsAllSet: 0b1100 } })
```

**Keluaran**

```
{ "_id": 2, "flags": 12 },
{ "_id": 3, "flags": 14 }
```

Dalam contoh ini, kueri memeriksa dokumen di mana `flags` bidang memiliki semua bit yang ditetapkan oleh bitmask `0b1100` (yang mewakili nilai desimal 12). Dokumen dengan `_id` 2 dan 3 cocok dengan kriteria ini, karena nilai `flags` bidangnya memiliki semua bit yang diperlukan (bit paling tidak signifikan ke-3 dan ke-4).

## Contoh kode
<a name="bitsAllSet-code"></a>

Untuk melihat contoh kode untuk menggunakan `$bitsAllSet` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$bitsAnyClear`Operator di Amazon DocumentDB digunakan untuk mencocokkan dokumen di mana salah satu bit yang ditentukan dalam bidang dihapus (disetel ke 0). Ini dapat berguna untuk melakukan operasi bitwise pada nilai bidang yang disimpan dalam dokumen.

**Parameter**
+ `field`: Bidang untuk memeriksa.
+ `value`: Bitmask numerik yang menentukan bit mana yang harus diperiksa, atau daftar posisi bit yang akan diperiksa. Bitmask numerik dapat berupa biner (0b...), desimal, heksadesimal (0x...), oktal (0o...), atau biner (). BinData Dalam daftar posisi bit, posisi bit yang paling tidak signifikan adalah 0.

## Contoh (MongoDB Shell)
<a name="bitsAnyClear-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$bitsAnyClear` operator untuk memeriksa apakah ada bit yang jelas di `status` bidang `items` koleksi.

**Buat dokumen sampel**

```
db.items.insertMany([
  { "_id": 1, "status": 7 },
  { "_id": 2, "status": 15 },
  { "_id": 3, "status": 31 }
]);
```

**Contoh kueri**

```
db.items.find({ "status": { $bitsAnyClear: 8 } })
```

**Keluaran**

```
{ "_id" : 1, "status" : 7 }
```

Dalam contoh ini, kueri memeriksa dokumen di mana `status` bidang memiliki bit yang jelas (0) di bitmask `8` (biner`1000`). Dokumen dengan `status` nilai `7` (biner`111`) cocok dengan kueri, karena setidaknya satu bit jelas dalam bitmask yang disediakan. Bit bening yang cocok adalah bit ke-4 yang paling tidak signifikan.

## Contoh kode
<a name="bitsAnyClear-code"></a>

Untuk melihat contoh kode untuk menggunakan `$bitsAnyClear` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$bitsAnySet`Operator di Amazon DocumentDB digunakan untuk menanyakan dokumen di mana setidaknya satu bit diatur ke 1 dalam bit yang ditentukan di bidang. Operator ini memungkinkan Anda melakukan operasi bitwise pada nilai yang disimpan di bidang, memungkinkan kueri dan analisis data yang efisien dengan karakteristik bitwise.

**Parameter**
+ `field`: Nama bidang untuk menerapkan operasi bitwise ke.
+ `value`: Bitmask numerik yang menentukan bit mana yang harus diperiksa, atau daftar posisi bit yang akan diperiksa. Bitmask numerik dapat berupa biner (0b...), desimal, heksadesimal (0x...), oktal (0o...), atau biner (). BinData Dalam daftar posisi bit, posisi bit yang paling tidak signifikan adalah 0.

## Contoh (MongoDB Shell)
<a name="bitsAnySet-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$bitsAnySet` operator untuk menemukan dokumen di mana setidaknya satu bit diatur di `flags` lapangan.

**Buat dokumen sampel**

```
db.collection.insertMany([
  { _id: 1, flags: 0b1010 },
  { _id: 2, flags: 0b1100 },
  { _id: 3, flags: 0b0011 },
  { _id: 4, flags: 0b0100 }
]);
```

**Contoh kueri**

```
db.collection.find({
  flags: { $bitsAnySet: 0b1010 }
})
```

**Keluaran**

```
{ "_id" : 1, "flags" : 10 }
{ "_id" : 2, "flags" : 12 }
{ "_id" : 3, "flags" : 3 }
```

Query mengembalikan dokumen di mana setidaknya salah satu bit yang ditentukan dalam bitmask `0b1010` diatur di `flags` lapangan.

## Contoh kode
<a name="bitsAnySet-code"></a>

Untuk melihat contoh kode untuk menggunakan `$bitsAnySet` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$comment`Operator di Amazon DocumentDB digunakan untuk melampirkan komentar ke kueri. Ini dapat berguna untuk memberikan konteks atau informasi tambahan tentang kueri, yang dapat membantu untuk tujuan debugging atau pendokumentasian. Komentar terlampir akan muncul sebagai bagian dari output operasi seperti db.currentTop ().

**Parameter**
+ `string`: Komentar yang dilampirkan pada kueri.

## Contoh (MongoDB Shell)
<a name="comment-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$comment` operator di Amazon DocumentDB.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.users.find({ age: { $gt: 25 } }, { _id: 0, name: 1, age: 1 }).comment("Retrieve users older than 25");
```

**Keluaran**

```
{ "name" : "John Doe", "age" : 30 }
{ "name" : "Bob Johnson", "age" : 35 }
```

## Contoh kode
<a name="comment-code"></a>

Untuk melihat contoh kode untuk menggunakan `$comment` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$elemMatch`Operator di Amazon DocumentDB digunakan untuk menanyakan bidang array dan mengembalikan dokumen di mana setidaknya satu elemen dalam array cocok dengan kriteria yang ditentukan. Operator ini sangat berguna ketika Anda memiliki struktur data yang kompleks dengan array bersarang atau dokumen yang disematkan.

Perencana versi 2.0 menambahkan dukungan indeks untuk`$elemMatch`.

**Parameter**
+ `field`: Bidang array untuk query.
+ `query`: Kriteria untuk mencocokkan dengan elemen array.

 

**Menggunakan `$elemMatch` dalam `$all` ekspresi**

Lihat [Menggunakan `$elemMatch` dalam `$all` ekspresi](functional-differences.md#functional-differences.elemMatch) batasan mengenai penggunaan `$elemMatch` operator dalam sebuah `$all` ekspresi.

## Contoh (MongoDB Shell)
<a name="elemMatch-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$elemMatch` operator untuk menemukan dokumen di mana `parts` array memiliki setidaknya satu elemen yang cocok dengan kriteria yang ditentukan.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.col.find({
  parts: { "$elemMatch": { part: "xyz", qty: { $lt: 11 } } }
})
```

**Keluaran**

```
{ "_id" : 1, "parts" : [ { "part" : "xyz", "qty" : 10 }, { "part" : "abc", "qty" : 20 } ] }
{ "_id" : 2, "parts" : [ { "part" : "xyz", "qty" : 5 }, { "part" : "abc", "qty" : 10 } ] }
```

## Contoh kode
<a name="elemMatch-code"></a>

Untuk melihat contoh kode untuk menggunakan `$elemMatch` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('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>

`$eq`Operator di Amazon DocumentDB digunakan untuk mencocokkan dokumen di mana nilai bidang sama dengan nilai yang ditentukan. Operator ini biasanya digunakan dalam `find()` metode untuk mengambil dokumen yang memenuhi kriteria yang ditentukan.

**Parameter**
+ `field`: Bidang untuk memeriksa kondisi kesetaraan.
+ `value`: Nilai untuk dibandingkan dengan bidang.

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

Contoh berikut menunjukkan penggunaan `$eq` operator untuk menemukan semua dokumen di mana `name` bidang sama dengan`"Thai Curry Palace"`.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.restaurants.find({ name: { $eq: "Thai Curry Palace" } });
```

**Keluaran**

```
{ "_id" : ObjectId("68ee586f916df9d39f3d9414"), "name" : "Thai Curry Palace", "cuisine" : "Thai", "features" : [ "Private Dining" ] }
```

## Contoh kode
<a name="eq-code"></a>

Untuk melihat contoh kode untuk menggunakan `$eq` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk memeriksa apakah bidang ada dalam dokumen atau tidak. `$exists`sangat berguna saat bekerja dengan indeks jarang di Amazon DocumentDB, di mana bidang yang diindeks mungkin tidak ada di semua dokumen.

Untuk menggunakan indeks jarang yang telah Anda buat dalam kueri, Anda harus menggunakan klausa `$exists` pada bidang yang mencakup indeks tersebut. Jika Anda menghilangkan`$exists`, Amazon DocumentDB tidak akan menggunakan indeks jarang untuk kueri.

**Parameter**
+ `field`: Nama bidang untuk memeriksa keberadaan.
+ `value`: Nilai boolean (`true`atau`false`) yang menentukan apakah bidang harus ada (`true`) atau tidak ada (`false`) dalam dokumen yang cocok.

## Contoh (MongoDB Shell)
<a name="exists-examples"></a>

Contoh berikut menunjukkan penggunaan `$exists` operator dengan indeks jarang pada `special_diets` bidang dalam koleksi. `food`

**Buat dokumen sampel**

```
db.food.insertMany([
  { _id: 1, name: "Apple", special_diets: ["vegetarian", "gluten-free"] },
  { _id: 2, name: "Broccoli" },
  { _id: 3, name: "Chicken", special_diets: ["dairy-free"] }
]);
```

**Buat indeks jarang pada bidang `special\$1diets`**

```
db.food.createIndex({ "special_diets": 1 }, { sparse: true, name: "special_diets_sparse_asc" });
```

**Contoh kueri**

```
db.food.find({ "special_diets": { $exists: true } });
```

**Keluaran**

```
[
  { "_id" : 1, "name" : "Apple", "special_diets" : [ "vegetarian", "gluten-free" ] },
  { "_id" : 3, "name" : "Chicken", "special_diets" : [ "dairy-free" ] }
]
```

## Contoh kode
<a name="exists-code"></a>

Untuk melihat contoh kode untuk menggunakan `$exists` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Baru dari versi 4.0.

Tidak didukung oleh cluster elastis.

`$expr`Operator di Amazon DocumentDB memungkinkan Anda menggunakan ekspresi agregasi dalam bahasa kueri. Ini memungkinkan Anda untuk melakukan perbandingan dan perhitungan yang kompleks pada bidang dalam dokumen, mirip dengan cara Anda menggunakan tahapan pipeline agregasi.

**Parameter**
+ `expression`: Ekspresi yang mengembalikan nilai boolean, memungkinkan Anda untuk melakukan perbandingan dan perhitungan pada bidang dokumen.

## Contoh (MongoDB Shell)
<a name="expr-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$expr` operator untuk menemukan semua dokumen di mana `manufacturingCost` bidang lebih besar dari `price` bidang.

**Buat dokumen sampel**

```
db.inventory.insertMany([
  { item: "abc", manufacturingCost: 500, price: 100 },
  { item: "def", manufacturingCost: 300, price: 450 },
  { item: "ghi", manufacturingCost: 400, price: 120 }
]);
```

**Contoh kueri**

```
db.inventory.find({
  $expr: {
    $gt: ["$manufacturingCost", "$price"]
  }
})
```

**Keluaran**

```
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89a"), "item" : "abc", "manufacturingCost" : 500, "price" : 100 },
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89c"), "item" : "ghi", "manufacturingCost" : 400, "price" : 120 }
```

## Contoh kode
<a name="expr-code"></a>

Untuk melihat contoh kode untuk menggunakan `$expr` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$gt`Operator di Amazon DocumentDB digunakan untuk memilih dokumen di mana nilai bidang yang ditentukan lebih besar dari nilai yang ditentukan. Operator ini berguna untuk memfilter dan menanyakan data berdasarkan perbandingan numerik.

**Parameter**
+ `field`: Bidang untuk membandingkan.
+ `value`: Nilai untuk dibandingkan.

## Contoh (MongoDB Shell)
<a name="gt-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$gt` operator untuk menemukan semua dokumen di mana `age` bidang lebih besar dari 30.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.users.find({ age: { $gt: 30 } });
```

**Keluaran**

```
{ "_id" : ObjectId("6249e5c22a5d39884a0a0001"), "name" : "Jane", "age" : 32 },
{ "_id" : ObjectId("6249e5c22a5d39884a0a0002"), "name" : "Bob", "age" : 45 }
```

## Contoh kode
<a name="gt-code"></a>

Untuk melihat contoh kode untuk menggunakan `$gt` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$gte`Operator di Amazon DocumentDB digunakan untuk mencocokkan nilai yang lebih besar dari atau sama dengan nilai yang ditentukan. Operator ini berguna untuk memfilter dan menanyakan data berdasarkan perbandingan numerik.

**Parameter**
+ `field`: Bidang untuk memeriksa nilai yang diberikan.
+ `value`: Nilai untuk dibandingkan dengan bidang.

## Contoh (MongoDB Shell)
<a name="gte-examples"></a>

Contoh berikut menunjukkan penggunaan `$gte` operator di Amazon DocumentDB untuk menemukan semua dokumen di mana bidang “usia” lebih besar dari atau sama dengan 25.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.users.find({ age: { $gte: 25 } }, { _id: 0, name: 1, age: 1 });
```

**Keluaran**

```
{ "name" : "Jane", "age" : 25 }
{ "name" : "Bob", "age" : 30 }
{ "name" : "Alice", "age" : 35 }
```

## Contoh kode
<a name="gte-code"></a>

Untuk melihat contoh kode untuk menggunakan `$gte` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$in`Operator di Amazon DocumentDB adalah operator kueri logis yang memungkinkan Anda menemukan dokumen di mana nilai bidang sama dengan nilai yang ditentukan dalam array.

**Parameter**
+ `field`: Bidang untuk memeriksa array yang disediakan.
+ `[value1, value2, ...]`: Array nilai untuk dicocokkan dengan bidang yang ditentukan.

 

**Dollar (`$`) dalam nama bidang**

Lihat [Dolar (\$1) dan titik (.) dalam nama bidang](functional-differences.md#functional-differences-dollardot) batasan terkait kueri bidang `$` awalan `$in` di objek bersarang.

## Contoh (MongoDB Shell)
<a name="in-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$in` operator untuk menemukan dokumen di mana `color` bidang adalah salah satu nilai dalam array yang disediakan.

**Buat dokumen sampel**

```
db.colors.insertMany([
  { "_id": 1, "color": "red" },
  { "_id": 2, "color": "green" },
  { "_id": 3, "color": "blue" },
  { "_id": 4, "color": "yellow" },
  { "_id": 5, "color": "purple" }
])
```

**Contoh kueri**

```
db.colors.find({ "color": { "$in": ["red", "blue", "purple"] } })
```

**Keluaran**

```
{ "_id": 1, "color": "red" },
{ "_id": 3, "color": "blue" },
{ "_id": 5, "color": "purple" }
```

## Contoh kode
<a name="in-code"></a>

Untuk melihat contoh kode untuk menggunakan `$in` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Baru dari versi 4.0.

Tidak didukung oleh cluster elastis.

`$jsonSchema`Operator di Amazon DocumentDB digunakan untuk memfilter dokumen berdasarkan skema JSON yang ditentukan. Operator ini memungkinkan Anda untuk menanyakan dokumen yang cocok dengan skema JSON tertentu, memastikan bahwa dokumen yang diambil mematuhi persyaratan struktural dan tipe data tertentu.

Dengan menggunakan operator kueri `$jsonSchema` evaluasi sebagai bagian dari pembuatan koleksi, Anda dapat memvalidasi skema dokumen yang dimasukkan ke dalam koleksi. Lihat [Menggunakan validasi skema JSON](json-schema-validation.md) untuk informasi tambahan.

**Parameter**
+ `required`(array): Menentukan bidang yang diperlukan dalam dokumen.
+ `properties`(object): Mendefinisikan tipe data dan kendala lainnya untuk setiap bidang dalam dokumen.

## Contoh (MongoDB Shell)
<a name="jsonSchema-examples"></a>

Contoh berikut menunjukkan penggunaan `$jsonSchema` operator untuk memfilter `employees` koleksi untuk hanya mengambil dokumen yang memiliki`name`, `employeeId` dan `age` bidang, dan `employeeId` bidang adalah jenis. `string`

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.employees.aggregate([
  { $match: {
    $jsonSchema: {
      required: ["name", "employeeId", "age"],
      properties: { "employeeId": { "bsonType": "string" } }
    }
  }}
]);
```

**Keluaran**

```
{ "_id" : ObjectId("6908e8b61f77fc26b2ecd26f"), "name" : { "firstName" : "Emily", "lastName" : "Brown" }, "employeeId" : "2", "age" : 25 }
```

## Contoh kode
<a name="jsonSchema-code"></a>

Untuk melihat contoh kode untuk menggunakan `$jsonSchema` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$lt`Operator di Amazon DocumentDB digunakan untuk mencocokkan nilai yang kurang dari nilai yang ditentukan. Operator ini berguna untuk memfilter dan menanyakan data berdasarkan perbandingan numerik.

**Parameter**
+ `field`: Nama bidang untuk memeriksa.
+ `value`: Nilai untuk dibandingkan.

## Contoh (MongoDB Shell)
<a name="lt-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$lt` operator untuk mengambil dokumen di mana `Inventory.OnHand` nilai kurang dari 50.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.example.find({ "Inventory.OnHand": { $lt: 50 } })
```

**Keluaran**

```
{ "_id" : 1, "Inventory" : { "OnHand" : 25, "Sold" : 60 }, "Colors" : [ "Red", "Blue" ] }
{ "_id" : 3, "Inventory" : { "OnHand" : 10, "Sold" : 85 }, "Colors" : [ "Red", "Green" ] }
```

## Contoh kode
<a name="lt-code"></a>

Untuk melihat contoh kode untuk menggunakan `$lt` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$mod` kueri memilih dokumen di mana nilai bidang dibagi dengan pembagi memiliki sisa tertentu. Ini berguna untuk memfilter dokumen berdasarkan kondisi aritmatika modulo.

**Parameter**
+ `divisor`: Angka untuk dibagi dengan.
+ `remainder`: Nilai sisa yang diharapkan.

## Contoh (MongoDB Shell)
<a name="mod-query-examples"></a>

Contoh berikut menunjukkan menggunakan `$mod` operator untuk menemukan semua pesanan di mana kuantitas adalah angka ganjil.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.orders.find({ quantity: { $mod: [2, 1] } });
```

**Keluaran**

```
{ "_id" : 1, "item" : "Widget", "quantity" : 15 }
{ "_id" : 3, "item" : "Tool", "quantity" : 7 }
{ "_id" : 5, "item" : "Part", "quantity" : 9 }
```

Kueri ini mengembalikan dokumen di mana kuantitas dibagi 2 memiliki sisa 1, secara efektif memilih semua jumlah ganjil.

## Contoh kode
<a name="mod-query-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$mod` kueri, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$lte`Operator di Amazon DocumentDB digunakan untuk mencocokkan dokumen di mana nilai bidang tertentu kurang dari atau sama dengan nilai yang ditentukan. Operator ini berguna untuk memfilter dan menanyakan data berdasarkan perbandingan numerik.

**Parameter**
+ `field`: Bidang untuk membandingkan.
+ `value`: Nilai untuk dibandingkan.

## Contoh (MongoDB Shell)
<a name="lte-examples"></a>

Contoh berikut menunjukkan penggunaan `$lte` operator untuk mengambil dokumen di mana `quantity` bidang kurang dari atau sama dengan 10.

**Buat dokumen sampel**

```
db.inventory.insertMany([
  { item: "canvas", qty: 100 },
  { item: "paint", qty: 50 },
  { item: "brush", qty: 10 },
  { item: "paper", qty: 5 }
]);
```

**Contoh kueri**

```
db.inventory.find({ qty: { $lte: 10 } });
```

**Keluaran**

```
{ "_id" : ObjectId("..."), "item" : "brush", "qty" : 10 },
{ "_id" : ObjectId("..."), "item" : "paper", "qty" : 5 }
```

## Contoh kode
<a name="lte-code"></a>

Untuk melihat contoh kode untuk menggunakan `$lte` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk mengakses metadata yang terkait dengan eksekusi kueri saat ini. Operator ini terutama digunakan untuk operasi pencarian teks, di mana metadata dapat memberikan informasi tentang relevansi dokumen yang cocok.

**Parameter**
+ `textScore`: Mengambil skor pencarian teks untuk dokumen. Skor ini menunjukkan relevansi dokumen dengan kueri pencarian teks.

## Contoh (MongoDB Shell)
<a name="meta-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$meta` operator untuk mengambil skor pencarian teks untuk dokumen yang cocok dengan permintaan pencarian teks.

**Buat dokumen sampel**

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

**Buat indeks teks**

```
db.documents.createIndex({ content: "text" });
```

**Contoh kueri**

```
db.documents.find(
  { $text: { $search: "coffee" } },
  { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });
```

**Keluaran**

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

## Contoh kode
<a name="meta-code"></a>

Untuk melihat contoh kode untuk menggunakan `$meta` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk mencocokkan dokumen di mana nilai bidang tidak sama dengan nilai yang ditentukan. Ini adalah operator perbandingan yang dapat digunakan dalam predikat kueri untuk memfilter dokumen.

Perencana versi 2.0 menambahkan dukungan indeks untuk`$ne`.

**Parameter**
+ `field`: Bidang untuk memeriksa.
+ `value`: Nilai yang harus diperiksa.

## Contoh (MongoDB Shell)
<a name="ne-examples"></a>

Dalam contoh ini, kita akan menemukan semua dokumen dalam `users` koleksi di mana `status` bidangnya tidak sama dengan`"active"`.

**Buat dokumen sampel**

```
db.users.insertMany([
  { name: "John", status: "active" },
  { name: "Jane", status: "inactive" },
  { name: "Bob", status: "suspended" },
  { name: "Alice", status: "active" }
]);
```

**Contoh kueri**

```
db.users.find({ status: { $ne: "active" } });
```

**Keluaran**

```
[
  {
    _id: ObjectId('...'),
    name: 'Jane',
    status: 'inactive'
  },
  {
    _id: ObjectId('...'),
    name: 'Bob',
    status: 'suspended'
  }
]
```

## Contoh kode
<a name="ne-code"></a>

Untuk melihat contoh kode untuk menggunakan `$ne` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk mencocokkan nilai yang tidak ada dalam array yang ditentukan. Ini adalah kebalikan dari `$in` operator, yang cocok dengan nilai-nilai yang ada dalam array yang ditentukan.

Perencana versi 2.0 menambahkan dukungan indeks untuk`$nin`.

**Parameter**
+ `field`: Bidang untuk memeriksa.
+ `array`: Array nilai untuk memeriksa terhadap.

 

**Dollar (`$`) dalam nama bidang**

Lihat [Dolar (\$1) dan titik (.) dalam nama bidang](functional-differences.md#functional-differences-dollardot) batasan terkait kueri bidang `$` awalan `$nin` di objek bersarang.

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

Contoh berikut menunjukkan bagaimana menggunakan `$nin` operator untuk menemukan dokumen di mana `category` bidang tidak sama dengan “Fiksi” atau “Misteri”.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.books.find({
  category: {
    $nin: ["Fiction", "Mystery"]
  }
})
```

**Keluaran**

```
[
  {
    _id: ObjectId('...'),
    title: 'The Martian',
    author: 'Andy Weir',
    category: 'Science Fiction'
  },
  {
    _id: ObjectId('...'),
    title: 'The Alchemist',
    author: 'Paulo Coelho',
    category: 'Philosophy'
  }
]
```

## Contoh kode
<a name="nin-code"></a>

Untuk melihat contoh kode untuk menggunakan `$nin` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk mencocokkan dokumen di mana tidak ada kondisi kueri yang ditentukan yang benar. Ini mirip dengan operasi “NOR” logis, di mana hasilnya benar jika tidak ada operan yang benar.

**Parameter**
+ `expression1`: Ekspresi pertama untuk mengevaluasi.
+ `expression2`: Ekspresi kedua untuk mengevaluasi.
+ `expressionN`: Ekspresi tambahan untuk dievaluasi.

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

Contoh berikut menunjukkan penggunaan `$nor` operator dengan mengambil dokumen di mana `qty` bidang tidak kurang dari 20 dan `size` bidang tidak sama dengan “XL”.

**Buat dokumen sampel**

```
db.items.insertMany([
  { qty: 10, size: "M" },
  { qty: 15, size: "XL" },
  { qty: 25, size: "L" },
  { qty: 30, size: "XL" }
])
```

**Contoh kueri**

```
db.items.find({
  $nor: [
    { qty: { $lt: 20 } },
    { size: "XL" }
  ]
})
```

**Keluaran**

```
[
  { "_id" : ObjectId("..."), "qty" : 25, "size" : "L" }
]
```

## Contoh kode
<a name="nor-code"></a>

Untuk melihat contoh kode untuk menggunakan `$nor` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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`Operator digunakan untuk meniadakan hasil dari ekspresi yang diberikan. Ini memungkinkan Anda untuk memilih dokumen di mana kondisi yang ditentukan tidak cocok.

Perencana versi 2.0 menambahkan dukungan indeks untuk `$not {eq}` dan`$not {in}`.

**Parameter**
+ `expression`: Ekspresi untuk meniadakan.

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

Contoh berikut menunjukkan bagaimana menggunakan `$not` operator untuk menemukan dokumen di mana `status` bidang tidak sama dengan “aktif”.

**Buat dokumen sampel**

```
db.users.insertMany([
  { name: "John", status: "active" },
  { name: "Jane", status: "inactive" },
  { name: "Bob", status: "pending" },
  { name: "Alice", status: "active" }
]);
```

**Contoh kueri**

```
db.users.find({ status: { $not: { $eq: "active" } } });
```

**Keluaran**

```
[
  {
    _id: ObjectId('...'),
    name: 'Jane',
    status: 'inactive'
  },
  {
    _id: ObjectId('...'),
    name: 'Bob',
    status: 'pending'
  }
]
```

## Contoh kode
<a name="not-code"></a>

Untuk melihat contoh kode untuk menggunakan `$not` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk melakukan operasi OR logis pada array dari dua atau lebih ekspresi. Ia mengembalikan dokumen yang cocok dengan setidaknya salah satu ekspresi. Operator ini berguna ketika Anda perlu menanyakan dokumen yang memenuhi salah satu dari beberapa kondisi.

**Parameter**
+ `expression1`: Ekspresi pertama untuk mengevaluasi.
+ `expression2`: Ekspresi kedua untuk mengevaluasi.
+ `...`: Ekspresi tambahan untuk dievaluasi (opsional).

## Contoh (MongoDB Shell)
<a name="or-examples"></a>

Contoh berikut menunjukkan penggunaan `$or` operator untuk menemukan dokumen di mana `make` adalah "TruckForYou" dengan model “Heavy H1" atau" SportForYou "dengan model “Bolid 1".

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.cars.find({
  $or: [
    { make: "TruckForYou", model: "Heavy H1" },
    { make: "SportForYou", model: "Bolid 1" }
  ]
});
```

**Keluaran**

```
[
  {
    _id: ObjectId('...'),
    make: 'TruckForYou',
    model: 'Heavy H1',
    year: 2020
  },
  {
    _id: ObjectId('...'),
    make: 'SportForYou',
    model: 'Bolid 1',
    year: 2021
  }
]
```

## Contoh kode
<a name="or-code"></a>

Untuk melihat contoh kode untuk menggunakan `$or` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator memungkinkan Anda untuk melakukan pencocokan ekspresi reguler pada bidang string. Ini adalah alat yang ampuh untuk mencari dan memfilter dokumen berdasarkan pola yang kompleks.

**Parameter**
+ `regular expression`: Pola ekspresi reguler untuk mencocokkan dengan bidang.
+ `$options`: (opsional) Menyediakan opsi untuk memodifikasi perilaku pencarian, seperti sensitivitas huruf kecil, pencocokan global, dll.

## Contoh (MongoDB Shell)
<a name="regex-examples"></a>

Contoh berikut menunjukkan penggunaan `$regex` operator untuk mencari dokumen di mana bidang “nama” cocok dengan pola tertentu.

**Buat dokumen sampel**

```
db.users.insertMany([
  { name: "John Doe" },
  { name: "Jane Smith" },
  { name: "Alice Johnson" },
  { name: "Bob Williams" },
  { name: "Charlie Davis" }
]);
```

**Contoh kueri**

```
db.users.find({ name: { $regex: /^A/ } })
```

**Keluaran**

```
[
  { "_id" : ObjectId("..."), "name" : "Alice Johnson" }
]
```

Kueri ini akan mengembalikan semua dokumen di mana bidang “nama” dimulai dengan huruf “A”.

## Contoh kode
<a name="regex-code"></a>

Untuk melihat contoh kode untuk menggunakan `$regex` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$slice` proyeksi membatasi jumlah elemen array yang dikembalikan dalam hasil query. Ini memungkinkan Anda untuk mengambil sejumlah elemen tertentu dari awal atau akhir bidang array tanpa memuat seluruh array.

**Parameter**
+ `field`: Bidang array untuk proyek.
+ `count`: Jumlah elemen yang akan dikembalikan. Nilai positif mengembalikan elemen dari awal, nilai negatif dari akhir.

## Contoh (MongoDB Shell)
<a name="slice-projection-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan operator `$slice` proyeksi untuk mengembalikan hanya dua item pertama dari bidang array.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.inventory.find(
  {},
  { item: 1, tags: { $slice: 2 } }
)
```

**Keluaran**

```
{ "_id" : 1, "item" : "notebook", "tags" : [ "office", "school" ] }
{ "_id" : 2, "item" : "pen", "tags" : [ "office", "writing" ] }
{ "_id" : 3, "item" : "folder", "tags" : [ "office", "supplies" ] }
```

## Contoh kode
<a name="slice-projection-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$slice` proyeksi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$size` kueri cocok dengan dokumen di mana bidang array memiliki persis jumlah elemen yang ditentukan. Ini berguna untuk memfilter dokumen berdasarkan panjang array.

**Parameter**
+ `field`: Bidang array untuk memeriksa.
+ `count`: Jumlah pasti elemen array harus berisi.

## Contoh (MongoDB Shell)
<a name="size-query-examples"></a>

Contoh berikut menunjukkan menggunakan `$size` operator untuk menemukan semua produk yang memiliki tepat tiga tag.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.products.find({ tags: { $size: 3 } });
```

**Keluaran**

```
{ "_id" : 1, "name" : "Laptop", "tags" : [ "electronics", "computers", "portable" ] }
{ "_id" : 3, "name" : "Desk", "tags" : [ "furniture", "office", "workspace" ] }
```

## Contoh kode
<a name="size-query-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$size` kueri, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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`Operator digunakan untuk melakukan pencarian teks lengkap pada bidang yang diindeks teks dalam koleksi dokumen. Operator ini memungkinkan Anda untuk mencari dokumen yang berisi kata atau frasa tertentu, dan dapat dikombinasikan dengan operator kueri lain untuk memfilter hasil berdasarkan kriteria tambahan.

**Parameter**
+ `$search`: String teks untuk mencari.

## Contoh (MongoDB Shell)
<a name="text-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$text` operator untuk mencari dokumen yang berisi kata “minat” dan memfilter hasil berdasarkan bidang “star\$1rating”.

**Buat dokumen sampel**

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

**Buat indeks teks**

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

**Contoh kueri**

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

**Keluaran**

```
{ "_id" : 5, "star_rating" : 5, "comments" : "interesting couch" }
{ "_id" : 6, "star_rating" : 5, "comments" : "interested in couch for sale, year 2022" }
```

Perintah di atas mengembalikan dokumen dengan bidang yang diindeks teks yang berisi segala bentuk “minat” dan “star\$1rating” sama dengan 5.

## Contoh kode
<a name="text-code"></a>

Untuk melihat contoh kode untuk menggunakan `$text` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk memeriksa tipe data bidang dalam dokumen. Ini dapat digunakan ketika operasi atau validasi tipe spesifik diperlukan. `$type`Operator mengembalikan tipe BSON dari ekspresi yang dievaluasi. Tipe yang dikembalikan adalah string, yang sesuai dengan jenis bidang atau ekspresi.

Perencana versi 2.0 menambahkan dukungan indeks untuk`$type`.

**Parameter**
+ `expression`: Ekspresi untuk mengevaluasi.

## Contoh (MongoDB Shell)
<a name="type-examples"></a>

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.documents.find({
  $or: [
    { age: { $type: "number" } },
    { email: { $type: "string" } },
    { name: { $type: "string" } }
  ]
})
```

**Keluaran**

```
[
  { "_id": 1, "name": "John", "age": 30, "email": "john@example.com" },
  { "_id": 2, "name": "Jane", "age": "25", "email": 123456 }
]
```

Kueri ini akan mengembalikan dokumen di mana `age` bidangnya bertipe “angka”, `email` bidangnya bertipe “string”, dan `name` bidangnya bertipe “string”.

## Contoh kode
<a name="type-code"></a>

Untuk melihat contoh kode untuk menggunakan `$type` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------

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

Bagian ini memberikan informasi terperinci tentang operator pembaruan yang didukung oleh 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>

Operator `$` posisi memperbarui elemen array pertama yang cocok dengan kondisi kueri. Ini bertindak sebagai placeholder untuk posisi elemen array yang cocok.

**Parameter**
+ `field.$`: Bidang array dengan operator posisi untuk memperbarui elemen pencocokan pertama.

## Contoh (MongoDB Shell)
<a name="dollar-update-examples"></a>

Contoh berikut menunjukkan menggunakan operator `$` posisi untuk memperbarui elemen array tertentu.

**Buat dokumen sampel**

```
db.inventory.insertMany([
  { _id: 1, item: "Widget", quantities: [10, 20, 30] },
  { _id: 2, item: "Gadget", quantities: [5, 15, 25] }
]);
```

**Contoh kueri**

```
db.inventory.updateOne(
  { _id: 1, quantities: 20 },
  { $set: { "quantities.$": 22 } }
);
```

**Keluaran**

```
{
  "_id" : 1,
  "item" : "Widget",
  "quantities" : [ 10, 22, 30 ]
}
```

## Contoh kode
<a name="dollar-update-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$` posisi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$[]` semua posisi memperbarui semua elemen dalam array. Hal ini digunakan ketika Anda perlu memodifikasi setiap elemen dalam bidang array.

**Parameter**
+ `field.$[]`: Bidang array dengan operator semua posisi untuk memperbarui semua elemen.

## Contoh (MongoDB Shell)
<a name="dollarBrackets-update-examples"></a>

Contoh berikut menunjukkan menggunakan `$[]` operator untuk memperbarui semua elemen array.

**Buat dokumen sampel**

```
db.products.insertOne({
  _id: 1,
  name: "Laptop",
  prices: [1000, 1100, 1200]
});
```

**Contoh kueri**

```
db.products.updateOne(
  { _id: 1 },
  { $inc: { "prices.$[]": 50 } }
);
```

**Keluaran**

```
{
  "_id" : 1,
  "name" : "Laptop",
  "prices" : [ 1050, 1150, 1250 ]
}
```

## Contoh kode
<a name="dollarBrackets-update-code"></a>

Untuk melihat contoh kode untuk menggunakan `$[]` operator, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator posisi yang `$[<identifier>]` difilter memperbarui semua elemen array yang cocok dengan kondisi filter yang ditentukan. Hal ini digunakan dengan `arrayFilters` pilihan untuk selektif memperbarui elemen array.

**Parameter**
+ `field.$[identifier]`: Bidang array dengan operator posisi yang disaring.
+ `arrayFilters`: Array kondisi filter yang menentukan elemen mana yang akan diperbarui.

## Contoh (MongoDB Shell)
<a name="dollarIdentifier-update-examples"></a>

Contoh berikut menunjukkan menggunakan `$[<identifier>]` operator untuk memperbarui elemen array tertentu berdasarkan kondisi.

**Buat dokumen sampel**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  grades: [
    { subject: "Math", score: 85 },
    { subject: "Science", score: 92 },
    { subject: "History", score: 78 }
  ]
});
```

**Contoh kueri**

```
db.students.updateOne(
  { _id: 1 },
  { $inc: { "grades.$[elem].score": 5 } },
  { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
);
```

**Keluaran**

```
{
  "_id" : 1,
  "name" : "Alice",
  "grades" : [
    { "subject" : "Math", "score" : 90 },
    { "subject" : "Science", "score" : 97 },
    { "subject" : "History", "score" : 78 }
  ]
}
```

## Contoh kode
<a name="dollarIdentifier-update-code"></a>

Untuk melihat contoh kode untuk menggunakan `$[<identifier>]` operator, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$addToSet`Operator di Amazon DocumentDB digunakan untuk menambahkan nilai ke array hanya jika nilainya belum ada dalam array. Ini berguna untuk memastikan bahwa array berisi elemen unik.

**Parameter**
+ `field`: Bidang untuk memperbarui.
+ `value`: Nilai untuk ditambahkan ke bidang array. Ini bisa berupa nilai tunggal atau ekspresi.

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

Contoh berikut menunjukkan bagaimana menggunakan `$addToSet` operator untuk menambahkan elemen unik ke array.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.products.update(
  { "item": "apple" },
  { $addToSet: { "tags": "green" } }
)
```

**Keluaran**

```
{ "_id": 1, "item": "apple", "tags": ["fruit", "red", "round", "green"] }
```

Dalam contoh ini, `$addToSet` operator menambahkan tag “hijau” ke array “tag” dokumen di mana bidang “item” adalah “apel”. Karena “hijau” belum ada dalam array, itu ditambahkan.

## Contoh kode
<a name="addToSet-code"></a>

Untuk melihat contoh kode untuk menggunakan `$addToSet` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$bit`Operator di Amazon DocumentDB memungkinkan Anda melakukan operasi bitwise pada bit bidang tertentu. Ini dapat berguna untuk tugas-tugas seperti pengaturan, pembersihan, atau memeriksa status bit individu dalam angka.

**Parameter**
+ `field`: Bidang untuk melakukan operasi bitwise pada.
+ `and`: Nilai integer yang digunakan untuk melakukan operasi AND bitwise di lapangan.
+ `or`: Nilai integer yang digunakan untuk melakukan operasi OR bitwise di lapangan.
+ `xor`: Nilai integer yang digunakan untuk melakukan operasi XOR bitwise di lapangan.

## Contoh (MongoDB Shell)
<a name="bit-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$bit` operator untuk melakukan operasi bitwise pada bidang numerik.

**Buat dokumen sampel**

```
db.numbers.insert([
  { "_id": 1, "number": 5 },
  { "_id": 2, "number": 12 }
])
```

**Contoh kueri**

```
db.numbers.update(
  { "_id": 1 },
  { "$bit": { "number": { "and": 3 } } }
)
```

**Keluaran**

```
{
  "_id": 1,
  "number": 1
}
```

Dalam contoh ini, `$bit` operator digunakan untuk melakukan operasi bitwise AND pada bidang “angka” dokumen dengan 1. `_id` Hasilnya adalah bahwa nilai bidang “angka” diatur ke 1, yang merupakan hasil dari operasi bitwise AND antara nilai asli 5 dan nilai 3.

## Contoh kode
<a name="bit-code"></a>

Untuk melihat contoh kode untuk menggunakan `$bit` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk mengatur nilai bidang ke tanggal dan waktu saat ini. Operator ini berguna untuk memperbarui bidang secara otomatis dengan stempel waktu saat ini ketika dokumen dimasukkan atau diperbarui.

**Parameter**
+ `field`: Bidang untuk memperbarui dengan tanggal dan waktu saat ini.
+ `type`: (opsional) Menentukan jenis BSON untuk digunakan untuk tanggal saat ini. Bisa salah satu `date` atau`timestamp`.

## Contoh (MongoDB Shell)
<a name="currentDate-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$currentDate` operator untuk mengatur `lastModified` bidang ke tanggal dan waktu saat ini ketika dokumen baru dimasukkan.

**Buat dokumen sampel**

```
db.users.insert({
  name: "John Doe",
  email: "john.doe@example.com"
})
```

**Contoh kueri**

```
db.users.updateOne(
  { name: "John Doe" },
  { $currentDate: { lastModified: true } }
)
```

**Lihat dokumen yang diperbarui**

```
db.users.findOne({ name: "John Doe" })
```

**Keluaran**

```
{
  _id: ObjectId('...'),
  name: 'John Doe',
  email: 'john.doe@example.com',
  lastModified: ISODate('2025-10-25T22:50:29.963Z')
}
```

## Contoh kode
<a name="currentDate-code"></a>

Untuk melihat contoh kode untuk menggunakan `$currentDate` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan bersama dengan operator pembaruan lainnya, seperti `$push` dan`$addToSet`, untuk menambahkan beberapa nilai ke bidang array. Ini memungkinkan menambahkan beberapa elemen ke array dalam satu operasi, daripada harus menjalankan beberapa operasi pembaruan.

**Parameter**
+ `value`: Array nilai untuk ditambahkan ke bidang array.

## Contoh (MongoDB Shell)
<a name="each-examples"></a>

Contoh berikut menunjukkan menggunakan `$each` operator dengan `$push` operator untuk menambahkan beberapa elemen ke bidang array.

**Buat dokumen sampel**

```
db.fruits.insertOne({
  _id: 1,
  fruits: ["apple", "banana"]
})
```

**Contoh kueri**

```
db.fruits.updateOne(
  { _id: 1 },
  { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
)
```

**Lihat dokumen yang diperbarui**

```
db.fruits.findOne({ _id: 1 })
```

**Keluaran**

```
{
  _id: 1,
  fruits: [ 'apple', 'banana', 'cherry', 'durian', 'elderberry' ]
}
```

## Contoh kode
<a name="each-code"></a>

Untuk melihat contoh kode untuk menggunakan `$each` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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`Operator digunakan untuk menambah nilai bidang dengan jumlah tertentu. Ini digunakan untuk memperbarui bidang numerik, seperti penghitung atau peringkat, tanpa harus mengambil nilai saat ini, menghitung nilai baru, dan kemudian memperbarui bidang.

**Parameter**
+ `field`: Nama bidang untuk kenaikan.
+ `amount`: Jumlah yang digunakan untuk menambah bidang. Ini bisa menjadi nilai positif atau negatif.

## Contoh (MongoDB Shell)
<a name="inc-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$inc` operator untuk menambah `age` bidang dokumen.

**Buat dokumen sampel**

```
db.users.insertOne({_id: 123, name: "John Doe", age: 30})
```

**Contoh kueri**

```
db.users.updateOne({_id: 123}, {$inc: {age: 1}})
```

**Lihat dokumen yang diperbarui**

```
db.users.findOne({_id: 123})
```

**Keluaran**

```
{ "_id" : 123, "name" : "John Doe", "age" : 31 }
```

## Contoh kode
<a name="inc-code"></a>

Untuk melihat contoh kode untuk menggunakan `$inc` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$max` pembaruan memperbarui nilai bidang hanya jika nilai yang ditentukan lebih besar dari nilai bidang saat ini. Operator ini berguna untuk mempertahankan nilai maksimum di seluruh pembaruan.

**Parameter**
+ `field`: Bidang untuk memperbarui.
+ `value`: Nilai untuk membandingkan dengan nilai bidang saat ini.

## Contoh (MongoDB Shell)
<a name="max-update-examples"></a>

Contoh berikut menunjukkan menggunakan `$max` operator untuk memperbarui skor tertinggi yang tercatat untuk pemain.

**Buat dokumen sampel**

```
db.scores.insertMany([
  { _id: 1, player: "Alice", highScore: 85 },
  { _id: 2, player: "Bob", highScore: 92 },
  { _id: 3, player: "Charlie", highScore: 78 }
])
```

**Perbarui contoh**

```
db.scores.updateOne(
  { _id: 1 },
  { $max: { highScore: 95 } }
)
```

**Hasil**

`highScore`Bidang untuk Alice diperbarui menjadi 95 karena 95 lebih besar dari nilai saat ini 85.

```
{ "_id": 1, "player": "Alice", "highScore": 95 }
```

## Contoh kode
<a name="max-update-code"></a>

Untuk melihat contoh kode untuk menggunakan `$max` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

Operator `$min` pembaruan memperbarui nilai bidang hanya jika nilai yang ditentukan kurang dari nilai bidang saat ini. Operator ini berguna untuk mempertahankan nilai minimum di seluruh pembaruan.

**Parameter**
+ `field`: Bidang untuk memperbarui.
+ `value`: Nilai untuk membandingkan dengan nilai bidang saat ini.

## Contoh (MongoDB Shell)
<a name="min-update-examples"></a>

Contoh berikut menunjukkan menggunakan `$min` operator untuk memperbarui suhu terendah yang tercatat untuk stasiun cuaca.

**Buat dokumen sampel**

```
db.weather.insertMany([
  { _id: 1, station: "Station A", lowestTemp: 15 },
  { _id: 2, station: "Station B", lowestTemp: 20 },
  { _id: 3, station: "Station C", lowestTemp: 18 }
])
```

**Perbarui contoh**

```
db.weather.updateOne(
  { _id: 1 },
  { $min: { lowestTemp: 12 } }
)
```

**Hasil**

`lowestTemp`Bidang untuk Stasiun A diperbarui ke 12 karena 12 kurang dari nilai saat ini 15.

```
{ "_id": 1, "station": "Station A", "lowestTemp": 12 }
```

## Contoh kode
<a name="min-update-code"></a>

Untuk melihat contoh kode untuk menggunakan `$min` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$mul`Operator di Amazon DocumentDB digunakan untuk mengalikan nilai bidang dengan nomor tertentu. Ini dapat berguna untuk memperbarui beberapa dokumen secara atomik dan konsisten, seperti memperbarui mil penerbangan berdasarkan status kartu kredit.

**Parameter**
+ `field`: Bidang yang akan dikalikan.
+ `multiplier`: Angka untuk mengalikan nilai bidang dengan.

## Contoh (MongoDB Shell)
<a name="mul-examples"></a>

Contoh ini menunjukkan bagaimana menggunakan `$mul` operator untuk menggandakan `flight_miles` nilai untuk semua dokumen di mana `credit_card` bidang tersebut`true`.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.miles.update(
  { "credit_card": { "$eq": true } },
  { "$mul": { "flight_miles.$[]": NumberInt(2) } },
  { "multi": true }
);
```

**Keluaran**

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

Untuk pelanggan yang memiliki kartu kredit, mil penerbangan mereka telah berlipat ganda.

Operator array `$[]` posisional digunakan untuk menerapkan `$mul` operasi ke setiap elemen dalam `flight_miles` array.

## Contoh kode
<a name="mul-code"></a>

Untuk melihat contoh kode untuk menggunakan `$mul` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$pop`Operator di Amazon DocumentDB digunakan untuk menghapus elemen pertama atau terakhir dari bidang array. Ini sangat berguna ketika Anda perlu mempertahankan array ukuran tetap atau menerapkan struktur data seperti antrian dalam dokumen.

**Parameter**
+ `field`: Nama bidang array untuk menghapus elemen dari.
+ `value`: Nilai integer yang menentukan posisi elemen untuk menghapus. Nilai `1` menghapus elemen terakhir, sementara nilai `-1` menghapus elemen pertama.

## Contoh (MongoDB Shell)
<a name="pop-examples"></a>

Contoh ini menunjukkan bagaimana menggunakan `$pop` operator untuk menghapus elemen pertama dan terakhir dari bidang array.

**Buat dokumen sampel**

```
db.users.insertMany([
  { "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming", "hiking"] },
  { "_id": 2, "name": "Jane Smith", "hobbies": ["cooking", "gardening", "painting"] }
])
```

**Contoh kueri**

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

**Keluaran**

```
{ "_id" : 1, "name" : "John Doe", "hobbies" : [ "swimming", "hiking" ] }
{ "_id" : 2, "name" : "Jane Smith", "hobbies" : [ "cooking", "gardening" ] }
```

## Contoh kode
<a name="pop-code"></a>

Untuk melihat contoh kode untuk menggunakan `$pop` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$position`Pengubah di Amazon DocumentDB menentukan lokasi dalam array di `$push` mana operator menyisipkan elemen. Tanpa `$position` modifier, `$push` operator menyisipkan elemen ke akhir array.

**Parameter**
+ `field`: Bidang array untuk memperbarui.
+ `num`: Posisi dalam array di mana elemen harus dimasukkan, berdasarkan pengindeksan berbasis nol.

**Catatan**: Untuk menggunakan `$position` pengubah, itu harus muncul dengan `$each` pengubah.

## Contoh (MongoDB Shell)
<a name="position-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$position` operator untuk menyisipkan tugas pada posisi tertentu dalam sistem manajemen proyek.

**Buat dokumen sampel**

```
db.projects.insertOne({ "_id": 1, "name": "Website Redesign", "tasks": ["Design mockups"] })
```

**Contoh kueri 1 - Tambahkan tugas mendesak di awal**

```
db.projects.updateOne(
   { _id: 1 },
   {
     $push: {
        tasks: {
           $each: ["Security audit", "Performance review"],
           $position: 0
        }
     }
   }
)
```

**Keluaran 1**

```
{ "_id": 1, "name": "Website Redesign", "tasks": ["Security audit", "Performance review", "Design mockups"] }
```

**Contoh kueri 2 - Tambahkan tugas pada posisi tertentu**

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

**Keluaran 2**

```
{ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Code review", "Testing phase", "Deploy to store"] }
```

## Contoh kode
<a name="position-code"></a>

Untuk melihat contoh kode untuk menggunakan `$position` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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`Operator digunakan untuk menghapus dari array semua contoh nilai atau nilai yang cocok dengan kondisi tertentu. Operator ini berguna ketika Anda perlu menghapus elemen tertentu dari bidang array dalam dokumen.

**Parameter**
+ `field`: Nama bidang array dari mana untuk menghapus nilai (s).
+ `value`: Nilai atau kondisi yang menentukan elemen mana yang akan dihapus dari array.

## Contoh (MongoDB Shell)
<a name="pull-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$pull` operator untuk menghapus elemen dari bidang array.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.restaurants.updateMany(
  { cuisine: "Italian" },
  { $pull: { features: "Takeout" } }
)
```

**Keluaran**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

Kueri di atas menghapus fitur “Takeout” dari semua dokumen yang `cuisine` bidangnya “Italia”.

## Contoh kode
<a name="pull-code"></a>

Untuk melihat contoh kode untuk menggunakan `$pull` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$pullAll`Operator di Amazon DocumentDB digunakan untuk menghapus semua instance nilai yang ditentukan dari bidang array. Ini sangat berguna ketika Anda perlu menghapus beberapa elemen dari array dalam satu operasi.

**Parameter**
+ `field`: Nama bidang array dari mana untuk menghapus elemen.
+ `value`: Sebuah array nilai untuk menghapus dari bidang array.

## Contoh (MongoDB Shell)
<a name="pullAll-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$pullAll` operator untuk menghapus beberapa elemen dari bidang array.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.restaurants.update(
  { "name": "Taj Mahal" },
  { $pullAll: { "features": ["Private Dining", "Live Music"] } }
)
```

**Keluaran**

```
{
  "name": "Taj Mahal",
  "cuisine": "Indian",
  "features": []
}
```

## Contoh kode
<a name="pullAll-code"></a>

Untuk melihat contoh kode untuk menggunakan `$pullAll` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$push`Operator di Amazon DocumentDB digunakan untuk menambahkan item ke bidang array dalam dokumen. Operator ini sangat berguna ketika Anda perlu menambahkan data baru ke array yang ada tanpa menimpa seluruh array.

**Parameter**
+ `field`: Nama bidang array yang elemen baru harus ditambahkan.
+ `value`: Nilai yang akan ditambahkan ke array.
+ `position`: (opsional) Sebuah modifier yang menentukan posisi dalam array di mana elemen baru harus ditambahkan. Pengubah yang didukung termasuk `$` (tambahkan ke akhir array) dan `$[]` (tambahkan ke akhir array, mengabaikan filter array apa pun).

## Contoh (MongoDB Shell)
<a name="push-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$push` operator untuk menambahkan elemen baru ke bidang array dalam dokumen.

**Buat dokumen sampel**

```
db.users.insert([
  { _id: 1, name: "John Doe", hobbies: ["reading", "swimming"] },
  { _id: 2, name: "Jane Smith", hobbies: ["gardening", "cooking"] }
])
```

**Contoh kueri**

```
db.users.updateOne(
  { _id: 1 },
  { $push: { hobbies: "hiking" } }
)
```

**Keluaran**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

Setelah menjalankan pembaruan, dokumen dengan `hobbies` array `_id: 1` akan diperbarui`[&quot;reading&quot;, &quot;swimming&quot;, &quot;hiking&quot;]`.

## Contoh kode
<a name="push-code"></a>

Untuk melihat contoh kode untuk menggunakan `$push` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$rename`Operator di Amazon DocumentDB digunakan untuk mengganti nama bidang dalam dokumen. Operator ini dapat sangat berguna ketika Anda perlu memperbarui struktur dokumen Anda atau menyelaraskannya dengan model data baru.

**Parameter**
+ `field`: Bidang yang akan diganti namanya.
+ `newName`: Nama baru untuk bidang.

## Contoh (MongoDB Shell)
<a name="rename-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$rename` operator untuk mengganti nama bidang menjadi `&quot;Date.DayOfWeek&quot;` dalam dokumen dengan `&quot;Date.DoW&quot;` bidang yang disetel ke. `&quot;DocName&quot;` `&quot;Document 1&quot;`

**Buat dokumen sampel**

```
db.example.insertOne({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**Contoh kueri**

```
db.example.update(
    { "DocName": "Document 1" },
    { $rename: { "Date.DoW": "Date.DayOfWeek" } }
)
```

**Keluaran**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DayOfWeek": "Saturday"
    },
    "Words": 2482
}
```

## Contoh kode
<a name="rename-code"></a>

Untuk melihat contoh kode untuk menggunakan `$rename` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

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

async function example() {
    const client = await MongoClient.connect('mongodb://<username>:<password>@<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>

`$set`Operator di Amazon DocumentDB digunakan untuk memperbarui nilai bidang tertentu dalam dokumen. Operator ini memungkinkan Anda untuk menambahkan bidang baru atau memodifikasi yang sudah ada dalam dokumen. Ini adalah operator pembaruan mendasar dalam driver MongoDB Java, yang kompatibel dengan Amazon DocumentDB.

**Parameter**
+ `field`: Bidang untuk memperbarui.
+ `value`: Nilai baru untuk bidang.

## Contoh (MongoDB Shell)
<a name="set-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$set` operator untuk memperbarui `Item` bidang dalam dokumen.

**Buat dokumen sampel**

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

**Contoh kueri**

```
db.example.update(
  { "Item": "Pen" },
  { $set: { "Item": "Gel Pen" } }
)
```

**Keluaran**

```
{
  "Item": "Gel Pen",
  "Colors": ["Red", "Green", "Blue", "Black"],
  "Inventory": {
    "OnHand": 244,
    "MinOnHand": 72
  }
}
```

## Contoh kode
<a name="set-code"></a>

Untuk melihat contoh kode untuk menggunakan `$set` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$setOnInsert`Operator di Amazon DocumentDB digunakan untuk menetapkan nilai bidang jika dokumen dimasukkan, tetapi tidak berpengaruh jika dokumen sedang diperbarui.

**Parameter**
+ `field`: Bidang yang akan diatur.
+ `value`: Nilai yang akan ditetapkan ke bidang.

## Contoh (MongoDB Shell)
<a name="setOnInsert-examples"></a>

Contoh berikut menunjukkan penggunaan `$setOnInsert` operator di Amazon DocumentDB. Ini membuat dokumen baru jika dokumen belum ada, tetapi tidak berpengaruh jika dokumen sedang diperbarui.

**Buat dokumen sampel**

```
db.users.insertOne({
  _id: 1,
  name: "John Doe",
  age: 30
})
```

**Contoh kueri 1 - Perbarui dokumen yang ada**

```
db.users.update(
  { _id: 1 },
  {
    $set: { age: 31 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**Keluaran 1**

```
{
  _id: 1,
  name: "John Doe",
  age: 31
}
```

Output menunjukkan bahwa dokumen telah diperbarui, tetapi `createdAt` bidang **TIDAK ditambahkan** karena dokumen sudah ada. `$setOnInsert`Operator hanya berlaku saat memasukkan dokumen baru.

**Contoh kueri 2 - Sisipkan dokumen baru (upsert)**

```
db.users.update(
  { _id: 2 },
  {
    $set: { name: "Jane Smith", age: 25 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**Keluaran 2**

```
{
  _id: 2,
  name: "Jane Smith", 
  age: 25,
  createdAt: ISODate("2025-10-31T09:57:52.459Z")
}
}
```

## Contoh kode
<a name="setOnInsert-code"></a>

Untuk melihat contoh kode untuk menggunakan `$setOnInsert` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Operator `$slice` pembaruan memodifikasi array dengan membatasi ukurannya. Ketika digunakan dengan `$push` operator, ini membatasi jumlah elemen dalam array, hanya menyimpan jumlah tertentu dari elemen terbaru atau tertua.

**Parameter**
+ `field`: Bidang array untuk memodifikasi.
+ `count`: Jumlah maksimum elemen yang harus disimpan. Nilai positif menjaga elemen N pertama, nilai negatif menjaga elemen N terakhir.

## Contoh (MongoDB Shell)
<a name="slice-update-examples"></a>

Contoh berikut menunjukkan cara menggunakan operator `$slice` pembaruan `$push` untuk mempertahankan array ukuran tetap dari skor terbaru.

**Buat dokumen sampel**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  scores: [85, 90, 78]
});
```

**Contoh kueri**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      scores: {
        $each: [92, 88],
        $slice: -3
      }
    }
  }
)
```

**Keluaran**

```
{
  "_id" : 1,
  "name" : "Alice",
  "scores" : [ 78, 92, 88 ]
}
```

Dalam contoh ini, `$slice: -3` pengubah hanya menyimpan tiga elemen terakhir setelah mendorong nilai baru ke array.

## Contoh kode
<a name="slice-update-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$slice` pembaruan, pilih tab untuk bahasa yang ingin Anda gunakan:

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

Pengubah `$sort` pembaruan memesan elemen array saat digunakan dengan `$push` operator. Ini mengatur elemen array dalam urutan naik atau turun berdasarkan nilai bidang tertentu atau elemen itu sendiri.

**Parameter**
+ `field`: Bidang array untuk memodifikasi.
+ `order`: Gunakan `1` untuk urutan menaik atau `-1` untuk urutan menurun.

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

Contoh berikut menunjukkan menggunakan `$sort` pengubah dengan `$push` untuk menambahkan skor kuis baru dan menjaga mereka diurutkan dalam urutan menurun.

**Buat dokumen sampel**

```
db.students.insertOne({
  _id: 1,
  name: "Bob",
  quizzes: [
    { score: 85, date: "2024-01-15" },
    { score: 92, date: "2024-02-10" }
  ]
});
```

**Contoh kueri**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      quizzes: {
        $each: [{ score: 78, date: "2024-03-05" }],
        $sort: { score: -1 }
      }
    }
  }
)
```

**Keluaran**

```
{
  "_id" : 1,
  "name" : "Bob",
  "quizzes" : [
    { "score" : 92, "date" : "2024-02-10" },
    { "score" : 85, "date" : "2024-01-15" },
    { "score" : 78, "date" : "2024-03-05" }
  ]
}
```

## Contoh kode
<a name="sort-update-code"></a>

Untuk melihat contoh kode untuk menggunakan pengubah `$sort` pembaruan, pilih tab untuk bahasa yang ingin Anda gunakan:

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

`$unset`Operator di Amazon DocumentDB digunakan untuk menghapus bidang tertentu dari dokumen. Ketika bidang dihapus menggunakan`$unset`, bidang dihapus dari dokumen, dan ukuran dokumen dikurangi sesuai. Ini dapat berguna ketika Anda ingin menghapus data yang tidak perlu dari dokumen Anda.

**Parameter**
+ `field`: Bidang untuk menghapus dari dokumen. Ini bisa berupa bidang tunggal atau jalur putus-putus ke bidang bersarang.

## Contoh (MongoDB Shell)
<a name="unset-examples"></a>

Contoh berikut menunjukkan cara menggunakan `$unset` operator untuk menghapus `Words` bidang dari dokumen dalam `example` koleksi.

**Buat dokumen sampel**

```
db.example.insert({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**Contoh kueri**

```
db.example.update(
    { "DocName" : "Document 1" },
    { $unset: { Words:1 } }
)
```

**Keluaran**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    }
}
```

Dalam contoh ini, `$unset` operator digunakan untuk menghapus `Words` bidang dari dokumen dengan `DocName` sama dengan “Dokumen 1". Dokumen yang dihasilkan tidak lagi berisi `Words` bidang.

## Contoh kode
<a name="unset-code"></a>

Untuk melihat contoh kode untuk menggunakan `$unset` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------