

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Amazon DocumentDB에서 지원되는 MongoDB API, 작업 및 데이터 형식
<a name="mongo-apis"></a>

Amazon DocumentDB(MongoDB 호환)은 MongoDB 워크로드를 지원하는 빠르고, 확장 가능하며, 가용성이 높은 완전관리형 문서 데이터베이스 서비스입니다. Amazon DocumentDB는 MongoDB 3.6, 4.0, 5.0 및 8.0 APIs. 이 단원에서는 지원되는 기능에 대해 설명합니다. MongoDB API 및 드라이버 사용에 대한 지원은 MongoDB 커뮤니티 포럼을 참조하십시오. Amazon DocumentDB 서비스 사용에 대한 지원은 해당 AWS 지원 팀에 문의하십시오. Amazon DocumentDB와 MongoDB 간의 기능적 차이는 [기능적 차이: Amazon DocumentDB 및 MongoDB](functional-differences.md)(을)를 참조하세요.

내부 전용이거나 완전 관리형 서비스에 해당되지 않는 MongoDB 명령 및 연산자는 지원되지 않으며, 지원 기능 목록에도 포함되지 않습니다.

출시 이후 50개 이상의 기능을 더 추가했으며 고객이 원하는 기능을 제공하기 위해 앞으로도 계속 노력할 것입니다. 최신 출시에 대한 자세한 내용은 [Amazon DocumentDB 공지 사항](https://aws.amazon.com/documentdb/resources/)을 참조하십시오.

지원되지 않는 기능 중 구축을 원하는 기능이 있는 경우, 계정 ID, 요청된 기능, 사용 사례를 포함한 이메일을 [Amazon DocumentDB 서비스 팀](mailto:documentdb-feature-request@amazon.com)에 보내 알려주십시오.
+ [데이터베이스 명령](#mongo-apis-database)
+ [쿼리 및 프로젝션 연산자](#mongo-apis-query)
+ [업데이트 연산자](#mongo-apis-update)
+ [지리 공간](#mongo-apis-geospatial)
+ [커서 메서드](#mongo-apis-cursor)
+ [집계 파이프라인 연산자](#mongo-apis-aggregation-pipeline)
+ [데이터 타입](#mongo-apis-data-types)
+ [인덱스](#mongo-apis-indexes)

## 데이터베이스 명령
<a name="mongo-apis-database"></a>

**Topics**
+ [관리 명령](#mongo-apis-dababase-administrative)
+ [집계](#mongo-apis-dababase-aggregation)
+ [Authentication](#mongo-apis-dababase-authentication)
+ [진단 명령](#mongo-apis-dababase-diagnostics)
+ [쿼리 및 쓰기 작업](#mongo-apis-dababase-query-write)
+ [역할 관리 명령](#mongo-apis-database-role-management)
+ [세션 명령](#mongo-apis-dababase-sessions)
+ [사용자 관리](#mongo-apis-dababase-user-management)
+ [샤딩 명령](#mongo-apis-dababase-sharding)

### 관리 명령
<a name="mongo-apis-dababase-administrative"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  제한 컬렉션  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  cloneCollectionAsCapped  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  collMod  |  부분적  |  부분적  |  부분적  |  부분적  |  부분적  | 
|  collMod: expireAfterSeconds  |  예  |  예  |  예  |  예  |  예  | 
|  convertToCapped  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  copydb  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  create  |  예  |  예  |  예  |  예  |  예  | 
|  createView  |  아니요  |  아니요  |  아니요  |  예  |  아니요  | 
|  createIndexes  |  예  |  예  |  예  |  예  |  예  | 
|  currentOp  |  예  |  예  |  예  |  예  |  예  | 
|  drop  |  예  |  예  |  예  |  예  |  예  | 
|  dropDatabase  |  예  |  예  |  예  |  예  |  예  | 
|  dropIndexes  |  예  |  예  |  예  |  예  |  예  | 
|  filemd5  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  getAuditConfig  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  killCursors  |  예  |  예  |  예  |  예  |  예  | 
|  killOp  |  예  |  예  |  예  |  예  |  예  | 
|  listCollections\$1  |  예  |  예  |  예  |  예  |  예  | 
|  listDatabases  |  예  |  예  |  예  |  예  |  예  | 
|  listIndexes  |  예  |  예  |  예  |  예  |  예  | 
|  reIndex  |  아니요  |  아니요  |  예  |  예  |  아니요  | 
|  renameCollection  |  예  |  예  |  예  |  예  |  아니요  | 
|  setAuditConfig  |  아니요  |  예  |  예  |  예  |  아니요  | 

\$1 필터 옵션의 `type` 키는 지원되지 않습니다.

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


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  aggregate  |  예  |  예  |  예  |  예  |  예  | 
|  count  |  예  |  예  |  예  |  예  |  예  | 
|  distinct  |  예  |  예  |  예  |  예  |  예  | 
|  mapReduce  |  아니요  |  아니요  |  아니요  |  예  |  아니요  | 

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


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  authenticate  |  예  |  예  |  예  |  예  |  예  | 
|  로그아웃  |  예  |  예  |  예  |  예  |  예  | 

### 진단 명령
<a name="mongo-apis-dababase-diagnostics"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  buildInfo  |  예  |  예  |  예  |  예  |  예  | 
|  collStats  |  예  |  예  |  예  |  예  |  예  | 
|  connPoolStats  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  connectionStatus  |  예  |  예  |  예  |  예  |  예  | 
|  dataSize  |  예  |  예  |  예  |  예  |  예  | 
|  dbHash  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  dbStats  |  예  |  예  |  예  |  예  |  예  | 
|  explain  |  예  |  예  |  예  |  예  |  예  | 
|  explain: executionStats  |  예  |  예  |  예  |  예  |  예  | 
|  기능  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  hostInfo  |  예  |  예  |  예  |  예  |  예  | 
|  listCommands  |  예  |  예  |  예  |  예  |  예  | 
|  profiler  |  [예](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [예](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [예](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  [예](https://docs.aws.amazon.com//documentdb/latest/developerguide/profiling.html)  |  아니요  | 
|  serverStatus  |  예  |  예  |  예  |  예  |  예  | 
|  top  |  예  |  예  |  예  |  예  |  예  | 

### 쿼리 및 쓰기 작업
<a name="mongo-apis-dababase-query-write"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  Change streams  |  [예](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [예](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [예](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  [예](https://docs.aws.amazon.com//documentdb/latest/developerguide/change_streams.html)  |  아니요  | 
|  delete  |  예  |  예  |  예  |  예  |  예  | 
|  find  |  예  |  예  |  예  |  예  |  예  | 
|  findAndModify  |  예  |  예  |  예  |  예  |  예  | 
|  getLastError  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  getMore  |  예  |  예  |  예  |  예  |  예  | 
|  getPrevError  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  GridFS  |  예  |  예  |  예  |  예  |  아니요  | 
|  삽입  |  예  |  예  |  예  |  예  |  예  | 
|  parallelCollectionScan  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  resetError  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  업데이트  |  예  |  예  |  예  |  예  |  예  | 
|  ReplaceOne  |  예  |  예  |  예  |  예  |  예  | 

### 역할 관리 명령
<a name="mongo-apis-database-role-management"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  createRole  |  예  |  예  |  예  |  예  |  아니요  | 
|  dropAllRolesFromDatabase  |  예  |  예  |  예  |  예  |  아니요  | 
|  dropRole  |  예  |  예  |  예  |  예  |  아니요  | 
|  grantRolesToRole  |  예  |  예  |  예  |  예  |  아니요  | 
|  revokeRolesFromRole  |  예  |  예  |  예  |  예  |  아니요  | 
|  revokePrivilegesFromRole  |  예  |  예  |  예  |  예  |  아니요  | 
|  rolesInfo  |  예  |  예  |  예  |  예  |  아니요  | 
|  updateRole  |  예  |  예  |  예  |  예  |  아니요  | 

### 세션 명령
<a name="mongo-apis-dababase-sessions"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  abortTransaction  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  commitTransaction  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  endSessions  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|   killAllSessions  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  killAllSessionsByPattern  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  killSessions  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  refreshSessions  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  startSession  |  아니요  |  예  |  예  |  예  |  아니요  | 

### 사용자 관리
<a name="mongo-apis-dababase-user-management"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  createUser  |  예  |  예  |  예  |  예  |  예  | 
|  dropAllUsersFromDatabase  |  예  |  예  |  예  |  예  |  예  | 
|  dropUser  |  예  |  예  |  예  |  예  |  예  | 
|  grantRolesToUser  |  예  |  예  |  예  |  예  |  예  | 
|  revokeRolesFromUser  |  예  |  예  |  예  |  예  |  예  | 
|  updateUser  |  예  |  예  |  예  |  예  |  예  | 
|  usersInfo  |  예  |  예  |  예  |  예  |  예  | 

### 샤딩 명령
<a name="mongo-apis-dababase-sharding"></a>


| 명령 | 엘라스틱 클러스터 | 
| --- | --- | 
|  abortReshardCollection  |  아니요  | 
|  addShard  |  아니요  | 
|  addShardToZone  |  아니요  | 
|  balancerCollectionStatus  |  아니요  | 
|  balancerStart  |  아니요  | 
|  balancerStatus  |  아니요  | 
|  balancerStop  |  아니요  | 
|  checkShardingIndex  |  아니요  | 
|  clearJumboFlag  |  아니요  | 
|  cleanupOrphaned  |  아니요  | 
|  cleanupReshardCollection  |  아니요  | 
|  commitReshardCollection  |  아니요  | 
|  enableSharding  |  예  | 
|  flushRouterConfig  |  아니요  | 
|  getShardMap  |  아니요  | 
|  getShardVersion  |  아니요  | 
|  isdbgrid  |  아니요  | 
|  listShards  |  아니요  | 
|  medianKey  |  아니요  | 
|  moveChunk  |  아니요  | 
|  movePrimary  |  아니요  | 
|  mergeChunks  |  아니요  | 
|  refineCollectionShardKey  |  아니요  | 
|  removeShard  |  아니요  | 
|  removeShardFromZone  |  아니요  | 
|  reshardCollection  |  아니요  | 
|  setAllowMigrations  |  아니요  | 
|  setShardVersion  |  아니요  | 
|  shardCollection  |  예  | 
|  shardingState  |  아니요  | 
|  split  |  아니요  | 
|  splitVector  |  아니요  | 
|  unsetSharding  |  아니요  | 
|  updateZoneKeyRange  |  아니요  | 

## 쿼리 및 프로젝션 연산자
<a name="mongo-apis-query"></a>

**Topics**
+ [배열 연산자](#mongo-apis-query-array-operators)
+ [Bitwise 연산자](#mongo-apis-query-bitwise-operators)
+ [설명 연산자](#mongo-apis-query-comment-operator)
+ [비교 연산자](#mongo-apis-query-comparison-operators)
+ [요소 연산자](#mongo-apis-query-element-operators)
+ [평가 쿼리 연산자](#mongo-apis-query-evaluation-operators)
+ [논리 연산자](#mongo-apis-query-logical-operators)
+ [프로젝션 연산자](#mongo-apis-projection-operators)

### 배열 연산자
<a name="mongo-apis-query-array-operators"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1all](all.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1elemMatch](elemMatch.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1size](size-query.md)  |  예  |  예  |  예  |  예  |  예  | 

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


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1bitsAllSet](bitsAllSet.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1bitsAnySet](bitsAnySet.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1bitsAllClear](bitsAllClear.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1bitsAnyClear](bitsAnyClear.md)  |  예  |  예  |  예  |  예  |  예  | 

### 설명 연산자
<a name="mongo-apis-query-comment-operator"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1comment](comment.md)  |  예  |  예  |  예  |  예  |  예  | 

### 비교 연산자
<a name="mongo-apis-query-comparison-operators"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1eq](eq.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1gt](gt.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1gte](gte.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1in](in.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1lt](lt.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1lte](lte.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1ne](ne.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1nin](nin.md)  |  예  |  예  |  예  |  예  |  예  | 

### 요소 연산자
<a name="mongo-apis-query-element-operators"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1exists](exists.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1type](type.md)  |  예  |  예  |  예  |  예  |  예  | 

### 평가 쿼리 연산자
<a name="mongo-apis-query-evaluation-operators"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1expr](expr.md)  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  [\$1jsonSchema](jsonSchema.md)  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  [\$1mod](mod-query.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1regex](regex.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1text](text.md)  |  아니요  |  아니요  |  예  |  예  |  아니요  | 
|  \$1where  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 

### 논리 연산자
<a name="mongo-apis-query-logical-operators"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1and](and.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1nor](nor.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1not](not.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1or](or.md)  |  예  |  예  |  예  |  예  |  예  | 

### 프로젝션 연산자
<a name="mongo-apis-projection-operators"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1](dollar-projection.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1elemMatch](elemMatch.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1meta](meta.md)  |  아니요  |  아니요  |  예  |  예  |  아니요  | 
|  [\$1slice](slice-projection.md)  |  예  |  예  |  예  |  예  |  예  | 

## 업데이트 연산자
<a name="mongo-apis-update"></a>

**Topics**
+ [배열 연산자](#mongo-apis-update-array)
+ [Bitwise 연산자](#mongo-apis-update-bitwise)
+ [필드 연산자](#mongo-apis-update-field)
+ [업데이트 한정자](#mongo-apis-update-modifiers)

### 배열 연산자
<a name="mongo-apis-update-array"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1](dollar-update.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1[]](dollarBrackets-update.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1[<identifier>]](dollarIdentifier-update.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1addToSet](addToSet.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1pop](pop.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1pullAll](pullAll.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1pull](pull.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1push](push.md)  |  예  |  예  |  예  |  예  |  예  | 

### Bitwise 연산자
<a name="mongo-apis-update-bitwise"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1bit](bit.md)  |  예  |  예  |  예  |  예  |  예  | 

### 필드 연산자
<a name="mongo-apis-update-field"></a>


| 연산자 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1currentDate](currentDate.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1inc](inc.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1max](max-update.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1min](min-update.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1mul](mul.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1rename](rename.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1set](set-update.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1setOnInsert](setOnInsert.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1unset](unset-update.md)  |  예  |  예  |  예  |  예  |  예  | 

### 업데이트 한정자
<a name="mongo-apis-update-modifiers"></a>


| 연산자 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1each](each.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1position](position.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1slice](slice-update.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1sort](sort-update.md)  |  예  |  예  |  예  |  예  |  예  | 

## 지리 공간
<a name="mongo-apis-geospatial"></a>

### 지오메트리 지정자
<a name="mongo-apis-geospatial-geometry-specifiers"></a>


| 쿼리 선택기 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1box  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1center  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1centerSphere  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1geometry](geometry.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1maxDistance](maxDistance.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1minDistance](minDistance.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1nearSphere](nearSphere.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1polygon  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1uniqueDocs  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 

### 쿼리 선택기
<a name="mongo-apis-geospatial-query-selectors"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1geoIntersects](geoIntersects.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1geoWithin](geoWithin.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1near](near.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1nearSphere](nearSphere.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1polygon  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1uniqueDocs  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 

## 커서 메서드
<a name="mongo-apis-cursor"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  cursor.batchSize()  |  예  |  예  |  예  |  예  |  예  | 
|  cursor.close()  |  예  |  예  |  예  |  예  |  예  | 
|  cursor.collation()  |  아니요  |  아니요  |  아니요  |  예  |  아니요  | 
|  cursor.comment()  |  예  |  예  |  예  |  예  |  예  | 
|  cursor.count()  |  예  |  예  |  예  |  예  |  예  | 
|  cursor.explain()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.forEach()  |  예  |  예  |  예  |  예  |  예  | 
|  cursor.hasNext()  |  예  |  예  |  예  |  예  |  예  | 
|  cursor.hint()  |  예  |  예  |  예  |  예  |  예\$1  | 
|  cursor.isClosed()  |  예  |  예  |  예  |  예  |  예  | 
|  cursor.isExhausted()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.itcount()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.limit()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.map()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.max()  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  cursor.maxScan()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.maxTimeMS()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.min()  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  cursor.next()  |  예  |  예  |  예  |  예  |  예  | 
|  cursor.noCursorTimeout()  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  cursor.objsLeftInBatch()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.pretty()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.readConcern()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.readPref()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.returnKey()  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  cursor.showRecordId()  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  cursor.size()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.skip()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.sort()  |  예  |  예  |  예  |  예  |  아니요  | 
|  cursor.tailable()  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  cursor.toArray()  |  예  |  예  |  예  |  예  |  아니요  | 

\$1 `hint` 인덱스는 인덱스 표현식과 함께 지원됩니다. 예를 들어 `db.foo.find().hint({x:1})`입니다.

## 집계 파이프라인 연산자
<a name="mongo-apis-aggregation-pipeline"></a>

**Topics**
+ [누적기 식](#mongo-apis-aggregation-pipeline-accumulator-expressions)
+ [산술 연산자](#mongo-apis-aggregation-pipeline-arithmetic)
+ [배열 연산자](#mongo-apis-aggregation-pipeline-array)
+ [부울 연산](#mongo-apis-aggregation-pipeline-boolean)
+ [비교 연산자](#mongo-apis-aggregation-pipeline-comparison)
+ [조건식 연산자](#mongo-apis-aggregation-pipeline-conditional)
+ [데이터 유형 연산자](#mongo-apis-aggregation-pipeline-data-type)
+ [데이터 크기 연산자](#mongo-apis-aggregation-pipeline-data-size)
+ [날짜 연산자](#mongo-apis-aggregation-pipeline-date)
+ [리터럴 연산자](#mongo-apis-aggregation-pipeline-literal)
+ [병합 연산자](#mongo-apis-aggregation-pipeline-merge)
+ [자연 연산자](#mongo-apis-aggregation-pipeline-natural)
+ [집합 연산자](#mongo-apis-aggregation-pipeline-set)
+ [단계 연산자](#mongo-apis-aggregation-pipeline-stage)
+ [문자열 연산자](#mongo-apis-aggregation-pipeline-string)
+ [시스템 변수](#mongo-apis-aggregation-pipeline-system-variables)
+ [텍스트 검색 연산자](#mongo-apis-aggregation-pipeline-text-search)
+ [유형 변환 연산자](#mongo-apis-aggregation-pipeline-type)
+ [변수 연산자](#mongo-apis-aggregation-pipeline-variable)
+ [기타 연산자](#mongo-apis-aggregation-pipeline-misc)

### 누적기 식
<a name="mongo-apis-aggregation-pipeline-accumulator-expressions"></a>


| 표현식 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1accumulator  |  -  |  -  |  아니요  |  아니요  |  아니요  | 
|  [\$1addToSet](addToSet-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1avg](avg.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1count](count.md)  |  -  |  -  |  아니요  |  아니요  |  아니요  | 
|  \$1covariancePop  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1covarianceSamp  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1denseRank  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1derivative  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1documentNumber  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1expMovingAvg  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1first](first.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1integral  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1last](last.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1max](max.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1min](min.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1push](push-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1rank  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1shift  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1stdDevPop  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1stdDevSamp  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1sum](sum.md)  |  예  |  예  |  예  |  예  |  예  | 

### 산술 연산자
<a name="mongo-apis-aggregation-pipeline-arithmetic"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1abs](abs.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1add](add.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1ceil](ceil.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1divide](divide.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1exp](exp.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1floor](floor.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1ln](ln.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1log](log.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1log10](log10.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1mod](mod.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1multiply](multiply.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1pow](pow.md)  |  아니요  |  아니요  |  아니요  |  예  |  아니요  | 
|  \$1round  |  -  |  -  |  아니요  |  아니요  |  아니요  | 
|  [\$1sqrt](sqrt.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1subtract](subtract.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1trunc  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 

### 배열 연산자
<a name="mongo-apis-aggregation-pipeline-array"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1arrayElemAt](arrayElemAt.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1arrayToObject](arrayToObject.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1concatArrays](concatArrays.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1filter](filter.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1first](first.md)  |  -  |  -  |  예  |  예  |  아니요  | 
|  [\$1in](in-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1indexOfArray](indexOfArray.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1isArray](isArray.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1last](last.md)  |  -  |  -  |  예  |  예  |  아니요  | 
|  [\$1objectToArray](objectToArray.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1range](range.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1reverseArray](reverseArray.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1reduce](reduce.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1size](size.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1slice](slice.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1zip](zip.md)  |  예  |  예  |  예  |  예  |  예  | 

### 부울 연산
<a name="mongo-apis-aggregation-pipeline-boolean"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1and](and-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1not](not-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1or](or-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 

### 비교 연산자
<a name="mongo-apis-aggregation-pipeline-comparison"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1cmp](cmp.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1eq](eq-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1gt](gt-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1gte](gte-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1lt](lt-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1lte](lte-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1ne](ne-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 

### 조건식 연산자
<a name="mongo-apis-aggregation-pipeline-conditional"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1cond](cond.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1ifNull](ifNull.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1switch](switch.md)  |  아니요  |  예  |  예  |  예  |  아니요  | 

### 데이터 유형 연산자
<a name="mongo-apis-aggregation-pipeline-data-type"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1type](type-aggregation.md)  |  예  |  예  |  예  |  예  |  예  | 

### 데이터 크기 연산자
<a name="mongo-apis-aggregation-pipeline-data-size"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1binarySize  |  -  |  -  |  아니요  |  아니요  |  아니요  | 
|  \$1bsonSize  |  -  |  -  |  아니요  |  아니요  |  아니요  | 

### 날짜 연산자
<a name="mongo-apis-aggregation-pipeline-date"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1dateAdd](dateAdd.md)  |  아니요  |  아니요  |  예  |  예  |  예  | 
|  [\$1dateDiff](dateDiff.md)  |  -  |  -  |  예  |  예  |  아니요  | 
|  \$1dateFromParts  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1dateFromString](dateFromString.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1dateSubtract](dateSubtract.md)  |  아니요  |  아니요  |  예  |  예  |  예  | 
|  \$1dateToParts  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1dateToString](dateToString.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1dateTrunc](dateTrunc.md)  |  -  |  -  |  아니요  |  예  |  아니요  | 
|  [\$1dayOfMonth](dayOfMonth.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1dayOfWeek](dayOfWeek.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1dayOfYear](dayOfYear.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1hour](hour.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1isoDayOfWeek](isoDayOfWeek.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1isoWeek](isoWeek.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1isoWeekYear](isoWeekYear.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1millisecond](millisecond.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1minute](minute.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1month](month.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1second](second.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1week](week.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1year](year.md)  |  예  |  예  |  예  |  예  |  예  | 

### 리터럴 연산자
<a name="mongo-apis-aggregation-pipeline-literal"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1literal](literal.md)  |  예  |  예  |  예  |  예  |  예  | 

### 병합 연산자
<a name="mongo-apis-aggregation-pipeline-merge"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1mergeObjects](mergeObjects.md)  |  예  |  예  |  예  |  예  |  예  | 

### 자연 연산자
<a name="mongo-apis-aggregation-pipeline-natural"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1natural](natural.md)  |  예  |  예  |  예  |  예  |  예  | 

### 집합 연산자
<a name="mongo-apis-aggregation-pipeline-set"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1allElementsTrue](allElementsTrue.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1anyElementTrue](anyElementTrue.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1setDifference](setDifference.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1setEquals](setEquals.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1setIntersection](setIntersection.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1setIsSubset](setIsSubset.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1setUnion](setUnion.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1setWindowFields  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 

### 단계 연산자
<a name="mongo-apis-aggregation-pipeline-stage"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1addFields](addFields.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1bucket](bucket.md)  |  아니요  |  아니요  |  아니요  |  예  |  아니요  | 
|  \$1bucketAuto  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1changeStream](changeStream.md)  |  예  |  예  |  예  |  예  |  아니요  | 
|  [\$1collStats](collStats.md)  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  [\$1count](count.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1currentOp](currentOp.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1facet  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1geoNear](geoNear.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1graphLookup  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1group](group.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1indexStats](indexStats.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1limit](limit.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1listLocalSessions  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1listSessions  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1lookup](lookup.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1match](match.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1merge](merge.md)  |  -  |  -  |  아니요  |  예  |  아니요  | 
|  [\$1out](out.md)  |  예  |  예  |  예  |  예  |  아니요  | 
|  \$1planCacheStats  |  -  |  -  |  아니요  |  아니요  |  아니요  | 
|  [\$1project](project.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1redact](redact.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1replaceRoot](replaceRoot.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1sample](sample.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1set](set-stage.md)  |  -  |  -  |  아니요  |  예  |  아니요  | 
|  \$1setWindowFields  |  -  |  -  |  아니요  |  아니요  |  아니요  | 
|  [\$1skip](skip.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1sort](sort.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1sortByCount  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  \$1unionWith  |  -  |  -  |  아니요  |  아니요  |  아니요  | 
|  [\$1unset](unset-stage.md)  |  -  |  -  |  아니요  |  예  |  아니요  | 
|  [\$1unwind](unwind.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1replaceWith](replaceWith.md)  |  아니요  |  아니요  |  아니요  |  예  |  아니요  | 
|  [\$1vectorSearch](vectorSearch.md)  |  아니요  |  아니요  |  아니요  |  예  |  아니요  | 

### 문자열 연산자
<a name="mongo-apis-aggregation-pipeline-string"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1concat](concat.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1indexOfBytes](indexOfBytes.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1indexOfCP](indexOfCP.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1ltrim](ltrim.md)  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  [\$1regexFind](regexFind.md)  |  -  |  -  |  예  |  예  |  아니요  | 
|  [\$1regexFindAll](regexFindAll.md)  |  -  |  -  |  예  |  예  |  아니요  | 
|  [\$1regexMatch](regexMatch.md)  |  -  |  -  |  예  |  예  |  아니요  | 
|  [\$1replaceAll](replaceAll.md)  |  -  |  -  |  예  |  예  |  아니요  | 
|  [\$1replaceOne](replaceOne.md)  |  -  |  -  |  예  |  예  |  아니요  | 
|  [\$1rtrim](rtrim.md)  |  아니요  |  예  |  예  |  예  |  아니요  | 
|  [\$1split](split.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1strcasecmp](strcasecmp.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1strLenBytes](strLenBytes.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1strLenCP](strLenCP.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1substr](substr.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1substrBytes](substrBytes.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1substrCP](substrCP.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1toLower](toLower.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1toUpper](toUpper.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1trim](trim.md)  |  아니요  |  예  |  예  |  예  |  아니요  | 

### 시스템 변수
<a name="mongo-apis-aggregation-pipeline-system-variables"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1\$1CURRENT  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1\$1DESCEND](DESCEND.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1\$1KEEP](KEEP.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1\$1PRUNE](PRUNE.md)  |  예  |  예  |  예  |  예  |  예  | 
|  \$1\$1REMOVE  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  [\$1ROOT](ROOT.md)  |  예  |  예  |  예  |  예  |  예  | 

### 텍스트 검색 연산자
<a name="mongo-apis-aggregation-pipeline-text-search"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1meta](meta-aggregation.md)  |  아니요  |  아니요  |  예  |  예  |  아니요  | 
|  [\$1search](search.md)  |  아니요  |  아니요  |  예  |  예  |  아니요  | 

### 유형 변환 연산자
<a name="mongo-apis-aggregation-pipeline-type"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1convert](convert.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  \$1isNumber  |  -  |  -  |  아니요  |  아니요  |  아니요  | 
|  [\$1toBool](toBool.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1toDate](toDate.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1toDecimal](toDecimal.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1toDouble](toDouble.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1toInt](toInt.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1toLong](toLong.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1toObjectId](toObjectId.md)  |  아니요  |  예  |  예  |  예  |  예  | 
|  [\$1toString](toString.md)  |  아니요  |  예  |  예  |  예  |  예  | 

### 변수 연산자
<a name="mongo-apis-aggregation-pipeline-variable"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  [\$1let](let.md)  |  예  |  예  |  예  |  예  |  예  | 
|  [\$1map](map.md)  |  예  |  예  |  예  |  예  |  예  | 

### 기타 연산자
<a name="mongo-apis-aggregation-pipeline-misc"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  \$1getField  |  -  |  -  |  아니요  |  아니요  |  아니요  | 
|  [\$1rand](rand.md)  |  -  |  -  |  아니요  |  예  |  아니요  | 
|  \$1sampleRate  |  -  |  -  |  아니요  |  아니요  |  아니요  | 

## 데이터 타입
<a name="mongo-apis-data-types"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  32비트 정수(int)  |  예  |  예  |  예  |  예  |  예  | 
|  64비트 정수(int)  |  예  |  예  |  예  |  예  |  예  | 
|  배열  |  예  |  예  |  예  |  예  |  예  | 
|  이진 데이터  |  예  |  예  |  예  |  예  |  예  | 
|  부울  |  예  |  예  |  예  |  예  |  예  | 
|  Date  |  예  |  예  |  예  |  예  |  예  | 
|  DBPointer  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  DBRefs  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  Decimal128  |  예  |  예  |  예  |  예  |  예  | 
|  배정밀도 실수  |  예  |  예  |  예  |  예  |  예  | 
|  JavaScript  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  JavaScript(범위 포함)  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  MaxKey  |  예  |  예  |  예  |  예  |  예  | 
|  MinKey  |  예  |  예  |  예  |  예  |  예  | 
|  Null  |  예  |  예  |  예  |  예  |  예  | 
|  객체  |  예  |  예  |  예  |  예  |  예  | 
|  ObjectId  |  예  |  예  |  예  |  예  |  예  | 
|  정규식  |  예  |  예  |  예  |  예  |  예  | 
|  문자열  |  예  |  예  |  예  |  예  |  예  | 
|  Symbol  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  타임스탬프  |  예  |  예  |  예  |  예  |  예  | 
|  정의되지 않음  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 

## 인덱스 및 인덱스 속성
<a name="mongo-apis-index"></a>

**Topics**
+ [인덱스](#mongo-apis-indexes)
+ [인덱스 속성](#mongo-apis-index-properties)

### 인덱스
<a name="mongo-apis-indexes"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  2dsphere  |  예  |  예  |  예  |  예  |  예  | 
|  2d 인덱스  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  복합 인덱스  |  예  |  예  |  예  |  예  |  예  | 
|  해시된 인덱스  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  Multikey 인덱스  |  예  |  예  |  예  |  예  |  예  | 
|  단일 필드 인덱스  |  예  |  예  |  예  |  예  |  예  | 
|  텍스트 인덱스  |  아니요  |  아니요  |  예  |  예  |  아니요  | 
|  와일드카드  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 

### 인덱스 속성
<a name="mongo-apis-index-properties"></a>


| 명령 | 3.6 | 4.0 | 5.0 | 8.0 | 엘라스틱 클러스터 | 
| --- | --- | --- | --- | --- | --- | 
|  배경  |  예  |  예  |  예  |  예  |  예  | 
|  대소문자 구분 안 함  |  아니요  |  아니요  |  아니요  |  예  |  아니요  | 
|  숨김  |  아니요  |  아니요  |  아니요  |  아니요  |  아니요  | 
|  부분적  |  아니요  |  아니요  |  예  |  예  |  아니요  | 
|  희소  |  예  |  예  |  예  |  예  |  예  | 
|  텍스트  |  아니요  |  아니요  |  예  |  예  |  아니요  | 
|  TTL  |  예  |  예  |  예  |  예  |  예  | 
|  고유  |  예  |  예  |  예  |  예  |  예  | 
|  벡터  |  아니요  |  아니요  |  예  |  예  |  아니요  | 

특정 MongoDB 연산자에 대한 자세한 내용은 다음 주제를 참조하세요.
+ [집계 파이프라인 연산자](mongo-apis-aggregation-pipeline-operators.md)
+ [Geospatial](mongo-apis-geospatial-operators.md)
+ [프로젝션 연산자](#mongo-apis-projection-operators)
+ [업데이트 연산자](mongo-apis-update-operators.md)

# 집계 파이프라인 연산자
<a name="mongo-apis-aggregation-pipeline-operators"></a>

이 섹션에서는 Amazon DocumentDB에서 지원하는 집계 파이프라인 연산자에 대한 자세한 정보를 제공합니다.

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

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

Amazon DocumentDB의 `$$DESCEND` 연산자는 `$redact` 파이프라인 단계 내에서 사용되는 특수 위치 배열 연산자입니다. 집계 파이프라인에 현재 문서로 내림하고 중첩 수준에 관계없이 모든 필드를 처리하도록 지시합니다.

`$redact` 스테이지에서 `$$DESCEND` 연산자를 발견하면 현재 문서의 모든 필드를 표시하고 파이프라인에서 더 아래로 처리합니다. 이는 문서의 구조를 유지하면서 조건에 따라 특정 필드를 선택적으로 수정하거나 정리하려는 경우에 유용합니다.

**파라미터**

없음.

## 예제(MongoDB 쉘)
<a name="DESCEND-examples"></a>

이 예제에서는 연`$$DESCEND`산자와 함께 `$redact` 단계를 사용하여 `code` 필드가 "Reg"와 같은 문서를 선택적으로 표시합니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="DESCEND-code"></a>

`$$DESCEND` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

redactPatients();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

redact_patients()
```

------

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

`$$KEEP` 시스템 변수는 집계 파이프라인의 `$redact` 스테이지와 함께 사용되어 현재 문서 또는 필드를 변경하지 않고 출력에 포함합니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="KEEP-examples"></a>

다음 예제에서는 Amazon DocumentDB 집계 파이프라인`$$KEEP`에서의 사용을 보여줍니다. 문서는 액세스가 "퍼블릭"과 같을 때만 보관되며, 그렇지 않으면 제거됩니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="KEEP-code"></a>

`$$KEEP` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

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

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

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

```
from pymongo import MongoClient

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

db = client.test
articles = db.articles

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

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

client.close()
```

------

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

`$$PRUNE` 시스템 변수는 집계 파이프라인의 `$redact` 단계와 함께 사용되어 결과에서 문서 또는 포함된 문서 수준을 제외합니다. 조건이 로 평가되면 `$$PRUNE`현재 문서 또는 하위 문서가 출력에서 제거됩니다. 일반적으로 `$$DESCEND` (문서를 보관 및 통과) 또는 `$$KEEP` (문서를 모든 수준에서 유지)와 함께 사용됩니다.

**파라미터**

없음. `$$PRUNE` 시스템 변수는 파라미터 없이 사용되며와 함께 사용해야 합니다`$redact`.

## 예제(MongoDB 쉘)
<a name="PRUNE-examples"></a>

다음 예제에서는와 `$$PRUNE` 함께를 사용하여 결과에서 30세 이상의 사용자를 제외`$redact`하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="PRUNE-code"></a>

`$$PRUNE` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

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

main();
```

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

```
from pymongo import MongoClient

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

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

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

------

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

Amazon DocumentDB의 `$ROOT` 연산자는 집계 파이프라인 내의 전체 입력 문서를 참조하는 데 사용됩니다. 이를 통해 중첩된 모든 필드 및 구조를 포함하여 전체 문서에 액세스하고 조작할 수 있습니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="ROOT-examples"></a>

이 예제에서는 `$ROOT`를 사용하여 처리 시기에 대한 메타데이터와 함께 전체 원본 문서를 캡처하는 감사 로그를 생성하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="ROOT-code"></a>

`$ROOT` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

createAuditLog();
```

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

```
from pymongo import MongoClient
from datetime import datetime

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

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

    print(result)
    client.close()

create_audit_log()
```

------

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

Amazon DocumentDB의 `$abs` 연산자는 숫자의 절대값을 반환합니다. 집계 파이프라인에서 숫자 필드에 수학 작업을 수행하는 데 사용할 수 있습니다.

**파라미터**
+ `number`: 절대 값이 반환될 숫자 표현식입니다.

## 예제(MongoDB 쉘)
<a name="abs-examples"></a>

이 예제에서는 연`$abs`산자를 사용하여 숫자 필드의 절대값을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="abs-code"></a>

`$abs` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

main();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

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

------

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

Amazon DocumentDB의 `$add` 연산자는 숫자 또는 날짜를 함께 추가하는 데 사용됩니다. 숫자 필드에 산술 연산을 수행하거나 날짜 필드에 여러 시간 단위를 추가하여 날짜 산술을 수행하는 데 사용할 수 있습니다.

**파라미터**
+ `expression1`: 추가할 첫 번째 숫자 또는 날짜입니다.
+ `expression2`: 추가할 두 번째 숫자 또는 날짜입니다.
+ `expression3`: (선택 사항) 추가할 추가 번호 또는 날짜입니다.

## 예제(MongoDB 쉘)
<a name="add-examples"></a>

다음 예제에서는 `$add` 연산자를 사용하여 두 숫자를 함께 추가하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

이 예제에서는 `$add` 연산자를 사용하여 각 문서에 대한 `a` 및 `b` 필드의 값을 추가하고 결과를 `sum` 필드에 저장합니다.

## 코드 예제
<a name="add-code"></a>

`$add` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

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

------

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

`$addToSet` 집계 연산자는 각 그룹에 대해 지정된 표현식에서 고유한 값의 배열을 반환합니다. `$group` 스테이지 내에서 고유한 값을 누적하여 중복을 자동으로 제거하는 데 사용됩니다.

**파라미터**
+ `expression`: 그룹의 각 문서에 대해 평가할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="addToSet-aggregation-examples"></a>

다음 예제에서는 `$addToSet` 연산자를 사용하여 각 고객에 대해 주문이 이루어진 고유한 도시를 수집하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="addToSet-aggregation-code"></a>

`$addToSet` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB 집계 파이프라인의 `$addFields` 단계를 사용하면 문서에 계산된 새 필드를 추가할 수 있습니다. 이는 파생되거나 변환된 데이터를 문서에 추가하는 데 유용할 수 있습니다.

**파라미터**
+ `newField`: 추가할 새 필드의 이름입니다.
+ `expression`: 새 필드의 값으로 확인되는 표현식입니다.

## 예제(MongoDB 쉘)
<a name="addFields-examples"></a>

다음 예제에서는를 `$addFields` 사용하여 `Inventory.OnHand` 및 필드를 기반으로 총 인벤토리를 계산`TotalInventory`하는 새 `Inventory.OrderQnty` 필드를 추가하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="addFields-code"></a>

`$addFields` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

console.log(result);

await client.close();
```

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

```
from pymongo import MongoClient

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

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

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

------

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

버전 4.0의 새로운 기능

연`$allElementsTrue`산자는 배열의 모든 요소가 true 값으로 평가되는지 확인하는 데 사용됩니다.

**파라미터**
+ `expression`: 배열로 평가되는 표현식입니다.

## 예제(MongoDB 쉘)
<a name="allElementsTrue-examples"></a>

다음 예제에서는를 사용하여 배열의 모든 요소가 true인지 확인하는 `$allElementsTrue` 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

이 예제에서 쿼리는 `scores` 배열의 모든 요소가 0보다 큰지 확인합니다. `scores` 배열에 거짓 값인 0이 포함되어 있기 때문에가 있는 문서는 `&quot;name&quot;: &quot;Jane&quot;` 제외됩니다.

## 코드 예제
<a name="allElementsTrue-code"></a>

`$allElementsTrue` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  console.log(result);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

example()
```

------

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

`$and` 집계 연산자는 여러 표현식을 평가하고 모든 표현식이 로 평가되는 `true` 경우에만를 반환합니다`true`. 표현식이 이면 `false`를 반환합니다`false`.

**파라미터**
+ `expressions`: 평가할 표현식의 배열입니다.

## 예제(MongoDB 쉘)
<a name="and-aggregation-examples"></a>

다음 예제에서는 `$and` 연산자를 사용하여 제품이 여러 기준을 충족하는지 확인하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="and-aggregation-code"></a>

`$and` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

버전 4.0의 새로운 기능

`$anyElementTrue` 연산자는 배열의 요소가 true인지 확인하는 데 사용됩니다.

**파라미터**
+ `field`: 평가할 배열 필드입니다.

## 예제(MongoDB 쉘)
<a name="anyElementTrue-examples"></a>

다음 예제에서는를 사용하여 배열의 요소가 true인지 확인하는 `$anyElementTrue` 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="anyElementTrue-code"></a>

`$anyElementTrue` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  console.log(result);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

example()
```

------

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

Amazon DocumentDB의 `$arrayElemAt` 연산자를 사용하면 인덱스 위치를 기준으로 배열에서 요소를 검색할 수 있습니다. 이는 문서의 배열 필드 내에서 특정 요소에 액세스해야 할 때 특히 유용합니다.

**파라미터**
+ `array`: 요소를 검색할 입력 배열입니다.
+ `index`: 검색할 요소의 0 기반 인덱스 위치입니다. 이 값은 음수가 아닌 정수여야 합니다.

## 예제(MongoDB 쉘)
<a name="arrayElemAt-examples"></a>

이 예제에서는 `$arrayElemAt` 연산자를 사용하여 `miles` 컬렉션의 `flight_miles` 배열에서 특정 요소를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

이 예제에서는 `$arrayElemAt` 연산자를 사용하여 각 문서에 대한 `flight_miles` 배열의 첫 번째 및 마지막 요소를 검색합니다.

## 코드 예제
<a name="arrayElemAt-code"></a>

`$arrayElemAt` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$arrayToObject` 연산자는 `$objectToArray` 연산자의 역순입니다. 키-값 페어 문서의 배열을 가져와서 단일 문서로 변환합니다. 이는 키-값 페어의 배열을 객체 또는 문서 구조로 다시 변환해야 할 때 특히 유용합니다.

**파라미터**
+ `array expression`: 배열로 확인되는 표현식입니다. 배열 요소는 (키)와 `k` (`v`값)의 두 필드가 있는 문서여야 합니다.

## 예제(MongoDB 쉘)
<a name="arrayToObject-examples"></a>

아래 예제에서는를 `$arrayToObject` 사용하여 키-값 페어 배열을 다시 문서로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

이 예제에서는 `$objectToArray` 연산자를 사용하여 `inventory` 객체를 키-값 페어의 배열로 변환합니다. 그런 다음 `$arrayToObject` 연산자를 사용하여 배열을 다시 문서로 변환하여 원래 객체 구조를 복원합니다.

## 코드 예제
<a name="arrayToObject-code"></a>

`$arrayToObject` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$avg` 집계 연산자는 단계에 입력되는 문서 전체에서 지정된 표현식의 평균 값을 계산합니다. 이 연산자는 문서 세트에서 숫자 필드 또는 표현식의 평균을 계산하는 데 유용합니다.

**파라미터**
+ `expression`: 평균을 계산하는 데 사용할 표현식입니다. 필드 경로(예: `"$field"`) 또는 표현식(예: `{ $multiply: ["$field1", "$field2"] }`)일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="avg-examples"></a>

다음 예제에서는 `$avg` 연산자를 사용하여 학생 문서 세트의 평균 점수를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="avg-code"></a>

`$avg` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

calculateAvgScore();
```

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

```
from pymongo import MongoClient

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

calculate_avg_score()
```

------

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

버전 8.0의 새로운 기능

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$bucket` 집계 단계를 사용하면 지정된 표현식 및 버킷 경계를 기반으로 입력 문서를 버킷으로 그룹화할 수 있습니다. 이는 특정 값 범위 또는 범주에 속하는 데이터를 분석하는 데 유용할 수 있습니다.

**파라미터**
+ `groupBy` (필수): 그룹화할 값을 지정하는 표현식입니다.
+ `boundaries` (필수): 버킷 경계를 정의하는 이중 값의 배열입니다. 문서는 지정된 경계 내에 속하는 `groupBy` 표현식 값을 기반으로 버킷에 할당됩니다.
+ `default` (선택 사항): `groupBy` 표현식 값이 지정된 경계에 속하지 않는 문서에 대해 출력되는 리터럴 값입니다.
+ `output` (선택 사항): 각 버킷에 대해 출력할 정보를 지정하는 객체입니다. `$sum`, `$avg``$min`, 및 같은 누적기 연산자를 사용하여 각 버킷에 대한 집계를 계산`$max`할 수 있습니다.

## 예제(MongoDB 쉘)
<a name="bucket-examples"></a>

다음 예제에서는 `$bucket` 스테이지를 사용하여 판매 데이터를 가격 범위별로 그룹화하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="bucket-code"></a>

`$bucket` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

버전 4.0의 새로운 기능

MongoDB와 마찬가지로 Amazon DocumentDB의 `$ceil` 연산자는 숫자를 가장 가까운 정수로 반올림합니다. 이는 숫자 필드에 수학 작업을 수행하고 결과가 정수인지 확인해야 할 때 유용합니다.

**파라미터**
+ `expression`: 반올림할 숫자 표현식입니다.

## 예제(MongoDB 쉘)
<a name="ceil-examples"></a>

이 예제에서는 `$ceil` 연산자를 사용하여 숫자 필드를 반올림하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="ceil-code"></a>

`$ceil` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Elastic 클러스터에서는 지원되지 않습니다.

`$changeStream` 집계 단계에서는 변경 스트림 커서를 열어 컬렉션에 대한 실시간 변경 사항을 모니터링합니다. 삽입, 업데이트, 교체 또는 삭제 작업이 발생할 때 변경 이벤트 문서를 반환합니다.

**파라미터**
+ `fullDocument`: 업데이트 작업을 위해 전체 문서를 반환할지 여부를 지정합니다. 옵션은 `default` 또는 `updateLookup`입니다.
+ `resumeAfter`: 선택 사항입니다. 토큰을 재개하여 변경 스트림의 특정 지점에서 계속합니다.
+ `startAtOperationTime`: 선택 사항입니다. 변경 스트림을 시작할 타임스탬프입니다.
+ `allChangesForCluster`: 선택 사항입니다. 부울 값입니다. 인 경우 `true`는 클러스터 전체의 모든 변경 사항을 감시합니다(관리자 데이터베이스의 경우). `false` (기본값)인 경우는 지정된 컬렉션만 감시합니다.

## 예제(MongoDB 쉘)
<a name="changeStream-examples"></a>

다음 예제에서는 `$changeStream` 스테이지를 사용하여 컬렉션에 대한 변경 사항을 모니터링하는 방법을 보여줍니다.

**쿼리 예제**

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

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

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

**출력**

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

## 코드 예제
<a name="changeStream-code"></a>

`$changeStream` 집계 단계 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient
import threading
import time

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

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

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

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

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

    client.close()

example()
```

------

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

Amazon DocumentDB의 `$cmp` 연산자는 두 값을 비교하고 상대 순서를 나타내는 정수 값을 반환하는 데 사용됩니다. 첫 번째 값이 각각 두 번째 값보다 작은지, 같은지 또는 큰지에 따라 두 표현식을 비교하고 -1, 0 또는 1의 정수 값을 반환하는 비교 연산자입니다.

**파라미터**
+ `expression1`: 비교할 첫 번째 표현식입니다.
+ `expression2`: 비교할 두 번째 표현식입니다.

## 예제(MongoDB 쉘)
<a name="cmp-examples"></a>

다음 예제에서는 연`$cmp`산자를 사용하여 두 숫자 값을 비교하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

이 예제에서 `$cmp` 연산자는 각 문서의 `value1` 및 `value2` 필드를 비교합니다. 결과는 다음과 같습니다.

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

## 코드 예제
<a name="cmp-code"></a>

`$cmp` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

다음은 `mongodb` 드라이버와 함께 Node.js 애플리케이션에서 `$cmp` 연산자를 사용하는 예입니다.

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

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

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

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

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

  console.log(result);

  await client.close();
}

main();
```

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

다음은 `pymongo` 드라이버와 함께 Python 애플리케이션에서 `$cmp` 연산자를 사용하는 예입니다.

```
from pymongo import MongoClient

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

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

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

print(result)

client.close()
```

Node.js 및 Python 예제의 출력은 MongoDB Shell 예제와 동일합니다.

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

------

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

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$collStats` 집계 단계는 MongoDB 셸의 `db.collection.stats()` 명령과 마찬가지로 지정된 컬렉션에 대한 통계를 제공합니다. 이 단계는 문서 수, 컬렉션의 총 크기, 다양한 성능 지표와 같은 컬렉션에 대한 정보를 검색하는 데 사용할 수 있습니다.

**파라미터**
+ `latencyStats`: (선택 사항) 지연 시간 통계 수집 옵션을 지정하는 문서입니다. 이 파라미터는 Amazon DocumentDB에서 지원되지 않습니다.
+ `recordStats`: (선택 사항) 레코드 통계 수집 옵션을 지정하는 문서입니다. 이 파라미터는 Amazon DocumentDB에서 지원되지 않습니다.
+ `queryExecStats`: (선택 사항) 쿼리 실행 통계를 수집하는 옵션을 지정하는 문서입니다. 이 파라미터는 Amazon DocumentDB에서 지원되지 않습니다.

## 예제(MongoDB 쉘)
<a name="collStats-examples"></a>

다음 예제에서는 `$collStats` 집계 단계를 사용하여 `db` 데이터베이스`test`에서 라는 컬렉션에 대한 통계를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="collStats-code"></a>

`$collStats` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

다음은 공식 MongoDB Node.js 드라이버를 사용하여 Node.js 애플리케이션에서 `$collStats` 집계 단계를 사용하는 방법의 예입니다.

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

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

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

  console.log(result);

  await client.close();
}

runCollStatsExample();
```

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

다음은 PyMongo 드라이버를 사용하여 Python 애플리케이션에서 `$collStats` 집계 단계를 사용하는 방법의 예입니다.

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

run_coll_stats_example()
```

------

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

Amazon DocumentDB의 `$concat` 집계 연산자는 문서의 여러 문자열을 연결(또는 결합)하여 애플리케이션에 반환할 수 있는 단일 문자열을 생성합니다. 이렇게 하면 문자열 조작이 데이터베이스 수준에서 수행되므로 애플리케이션에서 수행되는 작업이 줄어듭니다.

**파라미터**
+ `expression1`: 연결할 첫 번째 문자열입니다.
+ `expression2`: 연결할 두 번째 문자열입니다.
+ `...`: 연결할 추가 문자열(선택 사항).

## 예제(MongoDB 쉘)
<a name="concat-examples"></a>

이 예제에서는 사용자의 이름과 성을 연결하여 각 사용자의 전체 이름을 생성합니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="concat-code"></a>

`$concat` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  console.log(result);

  await client.close();
}

concatenateNames();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

concatenate_names()
```

------

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

Amazon DocumentDB의 `$concatArrays` 집계 연산자는 두 개 이상의 배열을 단일 배열로 연결하는 데 사용됩니다. 이는 추가 처리 또는 분석을 위해 여러 데이터 배열을 단일 배열로 결합해야 할 때 유용할 수 있습니다.

**파라미터**
+ `array1`: 연결할 첫 번째 배열입니다.
+ `array2`: 연결할 두 번째 배열입니다.
+ `[array3, ...]`: (선택 사항) 연결할 추가 배열입니다.

## 예제(MongoDB 쉘)
<a name="concatArrays-examples"></a>

다음 예제에서는 `$concatArrays` 연산자를 사용하여 두 배열을 단일 배열로 결합하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="concatArrays-code"></a>

`$concatArrays` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$cond` 연산자는 조건 표현식을 평가하고 두 개의 가능한 결과 표현식 중 하나를 반환하는 데 사용됩니다.

**파라미터**
+ `if`: 평가할 부울 표현식입니다.
+ `then`: 표현식이 true인 경우 반환할 `if` 표현식입니다.
+ `else`: 표현식이 false인 경우 반환할 `if` 표현식입니다.

## 예제(MongoDB 쉘)
<a name="cond-examples"></a>

다음 예제에서는 연`$cond`산자를 사용하여 사람의 연령에 따라 값을 반환하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="cond-code"></a>

`$cond` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient


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

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

    print(result)
    client.close()

example()
```

------

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

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$convert` 연산자는 값을 한 데이터 유형에서 다른 데이터 유형으로 변환하는 데 사용됩니다. 이 연산자는 문자열을 숫자로 변환하거나 날짜를 타임스탬프로 변환하는 등 다양한 유형의 데이터에 대한 작업을 수행해야 하는 경우에 유용합니다.

**파라미터**
+ `to`: 값을 변환할 대상 데이터 유형입니다. 지원되는 값은 `"string"`, `"double"`, `"long"`, `"int"`, `"date"` 및 `"boolean"`입니다.
+ `from`: 값의 현재 데이터 형식입니다. 지정하지 않으면 Amazon DocumentDB는 데이터 유형을 자동으로 감지하려고 시도합니다.
+ `onError`: (선택 사항) 변환에 실패할 경우 반환할 값입니다. 특정 값이거나 `"null"`, `"zerofill"`또는 특수 값 중 하나일 수 있습니다`"error"`.
+ `onNull`: (선택 사항) 입력 값이 인 경우 반환할 값입니다`null`. 특정 값이거나 `"null"`, `"zerofill"`또는 특수 값 중 하나일 수 있습니다`"error"`.

## 예제(MongoDB 쉘)
<a name="convert-examples"></a>

다음 예제에서는 `$convert` 연산자를 사용하여 문자열 값을 날짜로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="convert-code"></a>

`$convert` 명령 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(results)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$count` 집계 단계는가 단계로 전달하는 문서 수를 계산하는 데 사용됩니다. 집계 파이프라인의 최종 단계로 사용되어 이전 단계와 일치하는 총 문서 수를 반환하는 경우가 많습니다.

**파라미터**
+ `field`: 계산할 필드입니다. 이 파라미터는 선택 사항이며 제공되지 않은 경우 스테이지는 총 입력 문서 수를 계산합니다.

## 예제(MongoDB 쉘)
<a name="count-examples"></a>

다음 예제에서는 `$count` 스테이지를 사용하여 컬렉션의 총 문서 수를 가져오는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

이 예제에서는 `users` 컬렉션을 집계하고 `$count` 스테이지를 사용하여 총 문서 수를 계산합니다.

## 코드 예제
<a name="count-code"></a>

`$count` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

  await client.close();
}

countDocuments();
```

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

```
from pymongo import MongoClient

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

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

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

    client.close()

count_documents()
```

------

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

`$currentOp` 집계 단계에서는 데이터베이스에서 현재 실행 중인 작업에 대한 정보를 반환합니다. 이 단계는 집계 파이프라인에서 활성 쿼리 및 작업을 모니터링하는 데 유용합니다.

**파라미터**
+ `allUsers` (선택 사항): 로 설정하면 모든 사용자에 대한 작업을 `true`반환합니다. 기본값은 `false`입니다.
+ `idleConnections` (선택 사항): 로 설정하면에 유휴 연결이 `true`포함됩니다. 기본값은 `false`입니다.
+ `idleCursors` (선택 사항): 로 설정하면 유휴 커서에 대한 정보가 `true`포함됩니다. 기본값은 `false`입니다.
+ `idleSessions` (선택 사항): 로 설정하면 유휴 세션에 대한 정보가 `true`포함됩니다. 기본값은 `true`입니다.
+ `localOps` (선택 사항): 로 설정하면에 로컬 작업이 `true`포함됩니다. 기본값은 `false`입니다.

## 예제(MongoDB 쉘)
<a name="currentOp-examples"></a>

다음 예제에서는 `$currentOp` 집계 단계를 사용하여 활성 읽기 작업에 대한 정보를 검색하는 방법을 보여줍니다.

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="currentOp-code"></a>

`$currentOp` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

버전 5.0의 새로운 기능

Amazon DocumentDB의 `$dateAdd` 집계 연산자를 사용하면 날짜 및 시간 값에 기간을 추가할 수 있습니다.

**파라미터**
+ `date`: 기간을 추가할 날짜 및 시간 값입니다.
+ `duration`: `date` 값에 추가할 기간입니다. , `years`, , , `months`, `days``hours`, `weeks`에 대한 키가 있는 객체로 지정할 수 `minutes`있습니다`seconds`.
+ `timezone`: (선택 사항) 날짜 추가를 수행할 때 사용할 시간대입니다. 지정하지 않으면 Amazon DocumentDB 클러스터의 기본 시간대가 사용됩니다.

## 예제(MongoDB 쉘)
<a name="dateAdd-examples"></a>

다음 예제에서는 `$dateAdd` 연산자를 사용하여 날짜에 2일 및 12시간을 추가하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="dateAdd-code"></a>

`$dateAdd` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  console.log(result);

  await client.close();
}

example();
```

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

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

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

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

    print(result)

    client.close()

example()
```

------

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

버전 5.0의 새로운 기능

Elastic 클러스터에서는 지원되지 않습니다.

`$dateDiff` 집계 연산자는 지정된 단위로 두 날짜 간의 차이를 계산합니다. 시작 날짜와 종료 날짜 사이에 교차된 단위 경계 수를 반환합니다.

**파라미터**
+ `startDate`: 시작 날짜 표현식입니다.
+ `endDate`: 종료 날짜 표현식입니다.
+ `unit`: 차이의 시간 단위입니다. 지원되는 단위는 `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, 및 `second`입니다`millisecond`.

## 예제(MongoDB 쉘)
<a name="dateDiff-examples"></a>

다음 예제에서는 `$dateDiff` 연산자를 사용하여 주문 배치와 배송 사이의 일수를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="dateDiff-code"></a>

`$dateDiff` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

example()
```

------

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

Amazon DocumentDB의 `$dateFromString` 집계 연산자를 사용하면 날짜-시간 문자열을 날짜 객체로 변환할 수 있습니다. 이는 데이터가 문자열로 저장되지만 데이터에 대해 날짜 기반 작업을 수행해야 하는 경우에 유용합니다.

**파라미터**
+ `dateString`: 날짜 및 시간을 나타내는 문자열입니다.
+ `format`: (선택 사항) 형식을 지정하는 문자열입니다`dateString`. 제공되지 않으면 Amazon DocumentDB는 ISO-8601 형식으로 문자열을 구문 분석하려고 시도합니다.
+ `timezone`: (선택 사항) 시간대를 지정하는 문자열입니다. 제공되지 않은 경우 Amazon DocumentDB는 서버의 시간대를 사용합니다.
+ `onError`: (선택 사항) 변환에 실패할 경우 수행할 작업을 지정합니다. 가능한 값은 `'error'` (오류를 발생시키는 기본값), `'null'` (를 반환) 또는 `'replace'` ( 값을 `onErrorMessage` 옵션에 지정된 대체 문자열로 대체`null`)입니다.
+ `onErrorMessage`: (선택 사항) `onError`이 로 설정된 경우 `'replace'`이 옵션은 대체 문자열을 지정합니다.

## 예제(MongoDB 쉘)
<a name="dateFromString-examples"></a>

다음 예제에서는 `$dateFromString`를 사용하여 Amazon DocumentDB에서 날짜 문자열을 날짜 객체로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="dateFromString-code"></a>

`$dateFromString` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

버전 5.0의 새로운 기능

Amazon DocumentDB의 `$dateSubtract` 집계 연산자를 사용하면 날짜 값에서 지정된 기간을 뺄 수 있습니다.

**파라미터**
+ `date`: 날짜 또는 타임스탬프로 확인되는 날짜 표현식입니다.
+ `subtrahend`: 표현식에서 뺄 시간을 지정하는 기간 `date` 표현식입니다.
+ `unit`: `subtrahend` 표현식의 시간 단위를 지정하는 문자열입니다. 지원되는 단위는 "연도", "분기", "월", "주", "일", "시간", "분", "초", "밀리초"입니다.

## 예제(MongoDB 쉘)
<a name="dateSubtract-examples"></a>

다음 예제에서는 `$dateSubtract` 연산자를 사용하여 현재 날짜로부터 1년 전의 날짜를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="dateSubtract-code"></a>

`$dateSubtract` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

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

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$dateToString` 집계 연산자는 날짜 또는 타임스탬프 값을 문자열 표현으로 변환하는 데 사용됩니다. 이는 표시 또는 추가 처리를 위해 특정 방식으로 날짜 및 시간을 포맷해야 하는 경우에 유용합니다.

**파라미터**
+ `date`: 문자열로 변환할 날짜 또는 타임스탬프 값입니다.
+ `format`: 날짜를 표시해야 하는 형식을 지정하는 문자열입니다. 형식 문자열에는 4자리 연도의 `%Y` 경우 , 2자리 월의 `%m` 경우 , `%d`2자리 월의 경우와 같은 다양한 형식 지정자가 포함될 수 있습니다.
+ `timezone`: (선택 사항) 변환에 사용할 시간대입니다. 지정하지 않으면 Amazon DocumentDB 클러스터를 호스팅하는 서버의 시간대가 사용됩니다.
+ `onNull`: (선택 사항) `date` 파라미터가 인 경우 반환되는 값입니다`null`.

## 예제(MongoDB 쉘)
<a name="dateToString-examples"></a>

다음 예제에서는 연`$dateToString`산자를 사용하여 `missionLog` 컬렉션의 `logDate` 필드를 포맷하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="dateToString-code"></a>

`$dateToString` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

다음은 Node.js 애플리케이션에서 `$dateToString` 연산자를 사용하는 예입니다.

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

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

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

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

example();
```

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

다음은 Python 애플리케이션에서 `$dateToString` 연산자를 사용하는 예입니다.

```
from pymongo import MongoClient

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

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

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

example()
```

------

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

버전 8.0의 새로운 기능

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$dateTrunc` 집계 연산자는 날짜를 지정된 단위로 잘라냅니다.

**파라미터**
+ `date`: 날짜 또는 타임스탬프로 확인되는 날짜 표현식입니다.
+ `unit`: 하위 추적 표현식의 시간 단위를 지정하는 문자열입니다. 지원되는 단위는 `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, 및 `second`입니다`millisecond`.

## 예제(MongoDB 쉘)
<a name="dateTrunc-examples"></a>

다음 예제에서는 `$dateTrunc` 연산자를 사용하여 날짜를 시간으로 자르는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="dateTrunc-code"></a>

`$dateTrunc` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

example()
```

------

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

Amazon DocumentDB의 `$dayOfMonth` 집계 연산자는 지정된 날짜의 월중 날짜(1\$131)를 검색합니다. 이 연산자는 문서의 날짜 필드에서 월의 날짜를 그룹화, 필터링 또는 추출하는 데 유용합니다.

**파라미터**
+ `date expression`: 날짜 표현식은 문서의 날짜 필드, 날짜 객체 또는 날짜 문자열일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="dayOfMonth-examples"></a>

이 예제에서는 `$dayOfMonth` 연산자를 사용하여 문서의 날짜 필드에서 월의 날짜를 추출하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="dayOfMonth-code"></a>

`$dayOfMonth` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$dayOfWeek` 연산자는 지정된 날짜 필드에서 요일을 추출합니다. MongoDB와 동일한 동작인 1(일요일)에서 7(토요일) 사이의 숫자로 요일을 반환합니다.

**파라미터**
+ `date field`: 요일을 추출할 날짜 필드입니다.

## 예제(MongoDB 쉘)
<a name="dayOfWeek-examples"></a>

이 예제에서는 `$dayOfWeek` 연산자를 사용하여 `weather` 컬렉션의 `date` 필드에서 요일을 추출하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="dayOfWeek-code"></a>

`$dayOfWeek` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  console.log(result);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

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

------

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

Amazon DocumentDB의 `$dayOfYear` 연산자는 날짜의 날짜를 1에서 366 사이의 숫자로 반환합니다(윤년이 아닌 경우 365).

**파라미터**
+ `expression`: 연도의 날짜를 추출할 날짜 필드 또는 표현식입니다.

## 예제(MongoDB 쉘)
<a name="dayOfYear-examples"></a>

이 예제에서는 `$dayOfYear` 연산자를 사용하여 Amazon DocumentDB 컬렉션의 날짜 필드에서 연도의 날짜를 추출하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="dayOfYear-code"></a>

`$dayOfYear` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  console.log(result);

  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)

    client.close()

example()
```

------

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

Amazon DocumentDB 집계 파이프라인의 `$divide` 연산자는 한 숫자를 다른 숫자로 나누는 데 사용됩니다. 문서 내의 숫자 필드에 수학 연산을 수행하는 데 유용한 연산자입니다.

**파라미터**
+ `numerator`: 분할할 배당 또는 숫자입니다.
+ `denominator`: 나눕니다.

## 예제(MongoDB 쉘)
<a name="divide-examples"></a>

이 예제에서는 `$divide` 연산자를 사용하여 연간 급여 및 연간 근무 시간을 기준으로 직원의 시간당 요금을 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="divide-code"></a>

`$divide` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

calculateHourlyRate();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

calculate_hourly_rate()
```

------

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

`$eq` 집계 연산자는 두 값을 비교하고 값이 같`true`으면를 반환하고 그렇지 않으면를 반환합니다`false`.

**파라미터**
+ `expression1`: 비교할 첫 번째 값입니다.
+ `expression2`: 비교할 두 번째 값입니다.

## 예제(MongoDB 쉘)
<a name="eq-aggregation-examples"></a>

다음 예제에서는 `$eq` 연산자를 사용하여 제품 수량이 대상 값과 일치하는지 확인하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="eq-aggregation-code"></a>

`$eq` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$exp` 연산자를 사용하면 상수 e를 지정된 숫자로 올릴 수 있습니다.

**파라미터**
+ `expression`: 평가할 표현식입니다. 필드 참조, 산술 연산 및 기타 집계 단계를 포함한 모든 유효한 집계 표현식일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="exp-examples"></a>

다음 예제에서는 연`$exp`산자를 사용하여 `quantity` 필드가 `price` 필드보다 큰 모든 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="exp-code"></a>

`$exp` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

aggregateExp();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

aggregate_exp()
```

------

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

Amazon DocumentDB의 `$filter` 연산자는 배열의 각 요소에 필터 표현식을 적용하고 지정된 조건과 일치하는 요소만 포함하는 배열을 반환하는 데 사용됩니다. 이 연산자는 문서 내의 배열 필드에 대해 복잡한 필터링 작업을 수행해야 할 때 유용합니다.

**파라미터**
+ `input`: 필터링할 배열 필드입니다.
+ `as`: `cond` 표현식 내에서 `input` 배열의 각 요소에 사용할 변수 이름입니다.
+ `cond`: 지정된 요소를 출력 배열에 포함할지 여부를 결정하는 부울 표현식입니다.

## 예제(MongoDB 쉘)
<a name="filter-examples"></a>

다음 예제에서는 `$filter` 연산자를 사용하여 각 주문의 고객을 프로젝션하고 가격이 15보다 큰 항목 배열의 항목만 포함하는 새 배열 필드 paidItems를 생성하는 방법을 보여줍니다. 기본적으로 각 주문의 항목을 필터링하여 15개가 넘는 제품만 포함합니다.

**샘플 문서 생성**

```
db.orders.insertMany([
  { _id: 1, customer: "abc123", items: [
    { name: "Product A", price: 10, qty: 2 },
    { name: "Product B", price: 20, qty: 1 }
  ]},
  { _id: 2, customer: "def456", items: [
    { name: "Product C", price: 5, qty: 3 },
    { name: "Product D", price: 15, qty: 4 }
  ]},
  { _id: 3, customer: "ghi789", items: [
    { name: "Product E", price: 8, qty: 3 },
    { name: "Product F", price: 12, qty: 1 }
  ]}
]);
```

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="filter-code"></a>

`$filter` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  try {
    await client.connect();

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

    const result = await collection.aggregate([
      {
        $project: {
          customer: 1,
          paidItems: {
            $filter: {
              input: "$items",
              as: "item",
              cond: { $gt: ["$$item.price", 15] }
            }
          }
        }
      }
    ]).toArray();

    console.log(JSON.stringify(result, null, 2));

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

example();
```

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

```
from pymongo import MongoClient
from pprint import pprint

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

        result = list(collection.aggregate([
            {
                '$project': {
                    'customer': 1,
                    'paidItems': {
                        '$filter': {
                            'input': '$items',
                            'as': 'item',
                            'cond': { '$gt': ['$$item.price', 15] }
                        }
                    }
                }
            }
        ]))

        for doc in result:
            pprint(doc)

example()
```

------

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

버전 5.0의 새 버전입니다.

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$first` 연산자는 그룹화된 문서 세트에서 첫 번째 문서를 반환합니다. 일반적으로 집계 파이프라인에서 특정 조건과 일치하는 첫 번째 문서를 검색하는 데 사용됩니다.

**파라미터**
+ `expression`: 각 그룹의 첫 번째 값으로 반환할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="first-examples"></a>

다음 예제에서는 연`$first`산자를 사용하여 집계 중에 각 범주에 대해 발생한 첫 번째 항목 값을 검색하는 방법을 보여줍니다.

참고:는 파이프라인의 현재 문서 순서를 기반으로 첫 번째 문서를 `$first` 반환합니다. 특정 주문(예: 날짜, 가격 등)을 보장하려면 `$sort` 스테이지 전에 `$group` 스테이지를 사용해야 합니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="first-code"></a>

`$first` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  try {
    await client.connect();

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

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

    console.log(result);

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

example();
```

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

```
from pymongo import MongoClient
from pprint import pprint

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

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

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

        pprint(result)

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

    finally:
        if client:
            client.close()

example()
```

------

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

버전 4.0에서 새로 추가되었습니다.

Amazon DocumentDB의 `$floor` 연산자는 지정된 숫자보다 작거나 같은 가장 큰 정수를 반환합니다. 이 연산자는 숫자 값을 내림하는 데 유용합니다.

**파라미터**
+ `expression`: 반올림할 숫자 표현식입니다.

## 예제(MongoDB 쉘)
<a name="floor-examples"></a>

다음 예제에서는 `$floor` 연산자를 사용하여 십진수 값을 가장 가까운 정수로 반올림하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="floor-code"></a>

`$floor` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  try {
    await client.connect();

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

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

    console.log(result);

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

example();
```

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

```
from pymongo import MongoClient
from pprint import pprint

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

        db = client.test
        collection = db.numbers

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

        pprint(result)

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

    finally:
        if client:
            client.close()

example()
```

------

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

`$geoNear` 집계 단계는 지정된 지점에 근접한 순서대로 문서를 반환합니다. 포인트로부터의 거리를 계산하고 출력 문서에 거리를 포함합니다.

**파라미터**
+ `near`: GeoJSON 또는 레거시 좌표로 지정된 거리를 계산할 지점입니다.
+ `distanceField`: 계산된 거리를 저장할 필드 이름입니다.
+ `spherical`: 구형 지오메트리를 사용할지 여부를 나타내는 부울입니다(GeoJSON 포인트에 필요).
+ `maxDistance`: 선택 사항입니다. 중심점으로부터의 최대 거리입니다.
+ `minDistance`: 선택 사항입니다. 중심점과의 최소 거리입니다.
+ `query`: 선택 사항입니다. 적용할 추가 필터 기준입니다.
+ `limit`: 선택 사항입니다. 반환할 최대 문서 수입니다.
+ `key`: 선택 사항입니다. 여러 지리 공간 인덱스가 있는 경우 지리 공간 쿼리에 사용할 필드입니다.

## 예제(MongoDB 쉘)
<a name="geoNear-examples"></a>

다음 예제에서는 `$geoNear` 스테이지를 사용하여 지정된 위치에 가장 가까운 스토어를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

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

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="geoNear-code"></a>

`$geoNear` 집계 단계 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

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

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$group` 집계 단계를 사용하면 지정된 표현식별로 문서를 그룹화하고 그룹화된 데이터에 대해 다양한 누적 작업을 수행할 수 있습니다. 이는 그룹화된 데이터를 기반으로 합계, 평균 또는 기타 통계를 계산하는 등의 작업에 유용할 수 있습니다.

**파라미터**
+ `_id`: 입력 문서를 그룹화해야 하는 표현식을 지정합니다. 필드 이름, 계산된 표현식 또는 둘 다일 수 있습니다.
+ `accumulator expressions`: (선택 사항) 그룹화된 데이터에 적용해야 하는 하나 이상의 누적기 표현식입니다. 이러한 표현식은 위에서 언급한 누적기 연산자를 사용합니다.

## 예제(MongoDB 쉘)
<a name="group-examples"></a>

다음 예시에서는 고객을 도시별로 그룹화하고 각 도시의 총 주문 금액을 계산합니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="group-code"></a>

`$group` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

groupByCity();
```

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

```
from pymongo import MongoClient

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

group_by_city()
```

------

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

`$gt` 집계 연산자는 두 값을 비교하고 첫 번째 값이 두 번째 값보다 크`true`면를 반환하고, 그렇지 않으면를 반환합니다`false`.

**파라미터**
+ `expression1`: 비교할 첫 번째 값입니다.
+ `expression2`: 비교할 두 번째 값입니다.

## 예제(MongoDB 쉘)
<a name="gt-aggregation-examples"></a>

다음 예제에서는 `$gt` 연산자를 사용하여 가격 임계값을 초과하는 제품을 식별하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="gt-aggregation-code"></a>

`$gt` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        price: 1,
        expensive: { $gt: ["$price", 100] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'price': 1,
                'expensive': { '$gt': ['$price', 100] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$gte` 집계 연산자는 두 값을 비교하고 첫 번째 값이 두 번째 값보다 크거나 같`true`으면를 반환하고, 그렇지 않으면를 반환합니다`false`.

**파라미터**
+ `expression1`: 비교할 첫 번째 값입니다.
+ `expression2`: 비교할 두 번째 값입니다.

## 예제(MongoDB 쉘)
<a name="gte-aggregation-examples"></a>

다음 예제에서는 `$gte` 연산자를 사용하여 학생이 시험을 통과했는지 확인하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="gte-aggregation-code"></a>

`$gte` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        score: 1,
        passed: { $gte: ["$score", 70] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'score': 1,
                'passed': { '$gte': ['$score', 70] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$hour` 연산자는 날짜 또는 타임스탬프 필드에서 시간 구성 요소를 추출합니다.

**파라미터**
+ `dateExpression`: 연산자가 적용되는 날짜입니다. 이는 유효한 BSON 날짜(예: \$1createdAt 또는 날짜 리터럴과 같은 필드)로 확인되어야 합니다.

파라미터는 다음 형식의 문서로 지정할 수도 있습니다.

\$1 날짜: `&lt;dateExpression&gt;`, 시간대: `&lt;timezoneExpression&gt;` \$1

이렇게 하면가 시간대 인식 날짜 작업을 적용할 수 있습니다.

```
- `<tzExpression>`: (optional) The timezone of the operation result. It must be a valid expression that resolves to a string formatted as either an Olson Timezone Identifier or a UTC Offset. If no timezone is provided, the result is in UTC.
```

## 예제(MongoDB 쉘)
<a name="hour-examples"></a>

다음 예제에서는 `$hour` 연산자를 사용하여 날짜 필드에서 시간 구성 요소를 추출하고 그에 따라 데이터를 그룹화하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.events.insertMany([
  { timestamp: new Date("2023-04-01T10:30:00Z") },
  { timestamp: new Date("2023-04-01T12:45:00Z") },
  { timestamp: new Date("2023-04-02T08:15:00Z") },
  { timestamp: new Date("2023-04-02T16:20:00Z") },
  { timestamp: new Date("2023-04-03T23:59:00Z") }
]);
```

**쿼리 예제**

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

**출력**

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

이 쿼리는 `timestamp` 필드의 시간 구성 요소를 기준으로 이벤트를 그룹화하고 각 시간에 대한 이벤트 수를 계산합니다.

## 코드 예제
<a name="hour-code"></a>

`$hour` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

    const result = await collection.aggregate([
      {
        $project: {
          hour: { $hour: "$timestamp" }
        }
      },
      {
        $group: {
          _id: "$hour",
          count: { $sum: 1 }
        }
      },
      {
        $sort: { _id: 1 }
      }
    ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient
from datetime import datetime

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

        result = list(collection.aggregate([
            {
                "$project": {
                    "hour": {"$hour": "$timestamp"}
                }
            },
            {
                "$group": {
                    "_id": "$hour",
                    "count": {"$sum": 1}
                }
            },
            {
                "$sort": {"_id": 1}
            }
        ]))

        print(result)

    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        client.close()

example()
```

------

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

입력 표현식이 null 또는 정의되지 않은 것으로 평가되는 경우 연`$ifNull`산자를 사용하여 지정된 값을 반환합니다. 이 연산자는 기본값을 제공하거나 null/미정의 사례를 처리하려는 시나리오에서 유용할 수 있습니다.

**파라미터**
+ `expression`: 평가할 표현식입니다.
+ `replacement`:가 null 또는 정의되지 않은 것으로 `<expression>` 평가되는 경우 반환할 값입니다.

## 예제(MongoDB 쉘)
<a name="ifNull-examples"></a>

다음 예제에서는 `name` 필드가 null이거나 정의되지 않은 경우 연`$ifNull`산자를 사용하여 기본값을 제공하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="ifNull-code"></a>

`$ifNull` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  const collection = db.collection('users');

  const pipeline = [
    {
      $project: {
        _id: 1,
        name: { $ifNull: ["$name", "No Name"] }
      }
    }
  ];

  const cursor = await collection.aggregate(pipeline);

  await cursor.forEach(doc => {
    console.log(doc);
  });

  await client.close();

}

example();
```

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

```
from pymongo import MongoClient

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

    pipeline = [
        {
            "$project": {
                "_id": 1,
                "name": { "$ifNull": ["$name", "No Name"] }
            }
        }
    ]

    result = collection.aggregate(pipeline)

    for doc in result:
        print(doc)

    client.close()

example()
```

------

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

`$in` 집계 연산자는 배열 내에 지정된 값이 존재하는지 확인합니다. 배열에서 값이 발견`true`되면를 반환하고, `false` 그렇지 않으면를 반환합니다.

**파라미터**
+ `value`: 검색할 값입니다.
+ `array`: 검색할 배열입니다.

## 예제(MongoDB 쉘)
<a name="in-aggregation-examples"></a>

다음 예제에서는 `$in` 연산자를 사용하여 각 직원의 스킬 세트에 특정 스킬이 있는지 확인하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.employees.insertMany([
  { _id: 1, name: "Sarah", skills: ["Python", "JavaScript", "SQL"] },
  { _id: 2, name: "Mike", skills: ["Java", "C++", "Go"] },
  { _id: 3, name: "Emma", skills: ["Python", "Ruby", "Rust"] }
]);
```

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="in-aggregation-code"></a>

`$in` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        hasPython: { $in: ["Python", "$skills"] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'hasPython': { '$in': ['Python', '$skills'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$indexOfArray` 연산자는 배열에서 지정된 요소의 첫 번째 발생 인덱스를 찾는 데 사용됩니다. 이 연산자는 지정된 값과 일치하는 배열에서 첫 번째 요소의 0 기반 인덱스 위치를 반환합니다. 값을 찾을 수 없는 경우 -1을 반환합니다.

**파라미터**
+ `array`: 검색할 배열입니다.
+ `value`: 배열에서 검색할 값입니다.
+ `start`: (선택 사항) 검색을 시작할 배열의 위치입니다. 기본값은 0입니다.

## 예제(MongoDB 쉘)
<a name="indexOfArray-examples"></a>

다음 예제에서는 \$1indexOfArray 연산자를 사용하여 각 문서의 "fruits" 배열에서 요소 "mango"의 첫 번째 발생 인덱스를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="indexOfArray-code"></a>

`$indexOfArray` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        fruitIndex: { $indexOfArray: ["$fruits", "mango"] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'fruitIndex': { '$indexOfArray': ["$fruits", "mango"] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 \$1indexOfBytes 연산자는 문자의 바이트 위치에 따라 문자열 내에서 하위 문자열의 시작 인덱스를 찾는 데 사용됩니다. 이는 비 라틴어 스크립트에 있는 것과 같이 멀티바이트 문자를 포함할 수 있는 텍스트 데이터로 작업할 때 유용할 수 있습니다.

**파라미터**
+ `string`: 검색할 입력 문자열입니다.
+ `substring`: 입력 문자열 내에서 검색할 하위 문자열입니다.
+ `[<start>]`: (선택 사항) 검색의 시작 위치(0 기반)입니다. 지정하지 않으면 문자열의 시작 부분에서 검색이 시작됩니다.

## 예제(MongoDB 쉘)
<a name="indexOfBytes-examples"></a>

다음 예제에서는를 사용하여 데스크 위치를 나타내는 문자열 집합에서 첫 번째 하이픈 문자의 인덱스를 찾는 `$indexOfBytes` 방법을 보여줍니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
```

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="indexOfBytes-code"></a>

`$indexOfBytes` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await db.collection('people').aggregate([
    { $project: { stateLocation: { $indexOfBytes: ["$Desk", "-"] } } }
  ]).toArray();
  console.log(result);
  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']
    
    result = list(db.people.aggregate([
        { '$project': { 'stateLocation': { '$indexOfBytes': ['$Desk', '-'] } } }
    ]))
    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$indexOfCP` 연산자는 문자열 표현식 내에서 지정된 하위 문자열이 처음 발생한 인덱스를 코드 포인트(CP)에서 찾는 데 사용됩니다. 이는 문자열 필드에서 콘텐츠를 구문 분석하고 추출할 때 유용할 수 있습니다.

**파라미터**
+ `string expression`: 검색할 문자열입니다.
+ `substring`: 검색할 하위 문자열입니다.
+ `[<start>]`: (선택 사항) 검색을 시작할 위치(제로 기반 인덱스). 기본값은 0.

## 예제(MongoDB 쉘)
<a name="indexOfCP-examples"></a>

이 예제에서는 `$indexOfCP` 연산자를 사용하여 각 문서의 데스크 필드에서 하이픈 문자 -의 첫 번째 발생 인덱스를 찾습니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "_id":1, "name":"John Doe", "Manager":"Jane Doe", "Role":"Developer", "Desk": "Düsseldorf-BVV-021"},
  { "_id":2, "name":"John Stiles", "Manager":"Jane Doe", "Role":"Manager", "Desk": "Munich-HGG-32a"},
  { "_id":3, "name":"Richard Roe", "Manager":"Jorge Souza", "Role":"Product", "Desk": "Cologne-ayu-892.50"},
  { "_id":4, "name":"Mary Major", "Manager":"Jane Doe", "Role":"Solution Architect", "Desk": "Dortmund-Hop-78"}
])
```

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="indexOfCP-code"></a>

`$indexOfCP` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    { $project: { stateLocation: { $indexOfCP: [ "$Desk", "-"] } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient

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

result = list(collection.aggregate([
    { '$project': { 'stateLocation': { '$indexOfCP': [ '$Desk', '-' ] } } }
]))

print(result)

client.close()
```

------

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

Amazon DocumentDB의 `$indexStats` 집계 단계는 컬렉션 내 인덱스 사용에 대한 인사이트를 제공합니다. 이 연산자를 사용하면 인덱스의 액세스 패턴을 모니터링할 수 있으므로 인덱스 관리 및 최적화에 대해 정보에 입각한 결정을 내리는 데 도움이 될 수 있습니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="indexStats-examples"></a>

다음 예제에서는 `$indexStats` 연산자를 사용하여 Amazon DocumentDB 컬렉션의 인덱스 사용량을 분석하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.grocery.insertMany([
  { _id: 1, product: "milk", quantity: 10 },
  { _id: 2, product: "eggs", quantity: 20 },
  { _id: 3, product: "bread", quantity: 5 },
  { _id: 4, product: "cheese", quantity: 15 },
  { _id: 5, product: "apple", quantity: 8 }
]);
```

**쿼리 예제**

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

**출력**

```
[
  {
    "name": "_id_",
    "key": {
      "_id": 1
    },
    "host": "docdb-cluster-1.cluster-123456789.us-west-2.docdb.amazonaws.com",
    "accesses": {
      "ops": NumberLong(5),
      "since": ISODate("2023-04-06T12:34:56.789Z")
    }
  },
  {
    "name": "product_1",
    "key": {
      "product": 1
    },
    "host": "docdb-cluster-1.cluster-123456789.us-west-2.docdb.amazonaws.com",
    "accesses": {
      "ops": NumberLong(10),
      "since": ISODate("2023-04-06T12:34:56.789Z")
    }
  }
]
```

이 예제에서 `$indexStats` 연산자는 `_id_` 인덱스에 5번 액세스했고 마지막 재설정 또는 서버 재부팅 이후 `product_1` 인덱스에 10번 액세스했음을 보여줍니다.

## 코드 예제
<a name="indexStats-code"></a>

`$indexStats` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

indexStats();
```

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

```
from pymongo import MongoClient

def index_stats():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    result = list(db.grocery.aggregate([
        { '$indexStats': {} }
    ]))
    print(result)
    client.close()

index_stats()
```

------

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

Amazon DocumentDB의 `$isArray` 연산자는 문서의 필드가 배열인지 확인하는 데 사용됩니다. 이 연산자는 집계 파이프라인 및 조건식에서 배열 유형 필드를 처리하는 데 유용할 수 있습니다.

**파라미터**
+ `field`: 배열인지 확인할 필드 경로입니다.

## 예제(MongoDB 쉘)
<a name="isArray-examples"></a>

이 예제에서는 `$isArray` 연산자를 사용하여 "인벤토리" 필드가 배열인 문서를 식별하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="isArray-code"></a>

`$isArray` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  console.log(result);

  await client.close();
}

run();
```

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

```
from pymongo import MongoClient

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

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

print(result)

client.close()
```

------

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

Amazon DocumentDB의 `$isoDayOfWeek` 연산자는 날짜의 ISO 요일을 정수 값으로 반환합니다. ISO 주 날짜 시스템은 매주 월요일부터 일요일까지를 정의하며, 1주차는 해당 연도의 첫 번째 목요일이 포함된 주입니다.

**파라미터**
+ `expression`: ISO 요일을 반환할 날짜 표현식입니다.

## 예제(MongoDB 쉘)
<a name="isoDayOfWeek-examples"></a>

다음 예제에서는 `$isoDayOfWeek` 연산자를 사용하여 이벤트 문서 세트에 대한 ISO 요일을 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.events.insertMany([
  { _id: 1, eventDate: ISODate("2023-04-01T12:00:00Z") },
  { _id: 2, eventDate: ISODate("2023-04-02T12:00:00Z") },
  { _id: 3, eventDate: ISODate("2023-04-03T12:00:00Z") },
  { _id: 4, eventDate: ISODate("2023-04-04T12:00:00Z") },
  { _id: 5, eventDate: ISODate("2023-04-05T12:00:00Z") },
  { _id: 6, eventDate: ISODate("2023-04-06T12:00:00Z") },
  { _id: 7, eventDate: ISODate("2023-04-07T12:00:00Z") }
]);
```

**쿼리 예제**

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

**출력**

```
[
  { "_id": 1, "eventDate": ISODate("2023-04-01T12:00:00Z"), "isoDayOfWeek": 6 },
  { "_id": 2, "eventDate": ISODate("2023-04-02T12:00:00Z"), "isoDayOfWeek": 7 },
  { "_id": 3, "eventDate": ISODate("2023-04-03T12:00:00Z"), "isoDayOfWeek": 1 },
  { "_id": 4, "eventDate": ISODate("2023-04-04T12:00:00Z"), "isoDayOfWeek": 2 },
  { "_id": 5, "eventDate": ISODate("2023-04-05T12:00:00Z"), "isoDayOfWeek": 3 },
  { "_id": 6, "eventDate": ISODate("2023-04-06T12:00:00Z"), "isoDayOfWeek": 4 },
  { "_id": 7, "eventDate": ISODate("2023-04-07T12:00:00Z"), "isoDayOfWeek": 5 }
]
```

## 코드 예제
<a name="isoDayOfWeek-code"></a>

`$isoDayOfWeek` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await events.aggregate([
    {
      $project: {
        _id: 1,
        eventDate: 1,
        isoDayOfWeek: { $isoDayOfWeek: '$eventDate' }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(events.aggregate([
        {
            '$project': {
                '_id': 1,
                'eventDate': 1,
                'isoDayOfWeek': { '$isoDayOfWeek': '$eventDate' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$isoWeek` 연산자는 날짜의 ISO 주 번호를 반환합니다. ISO 주 날짜 시스템은 한 해의 주 번호를 매기는 방법으로, 새해의 첫 번째 주가 해당 연도의 첫 번째 목요일이 포함된 주입니다. 이는 새해의 첫 주가 1월 1일이 포함된 주인 그레고리 달력과 다릅니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="isoWeek-examples"></a>

다음 예제에서는 `$isoWeek` 연산자를 사용하여 지정된 날짜의 ISO 주 번호를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.dates.insertMany([
  { _id: 1, date: new ISODate("2022-01-01") },
  { _id: 2, date: new ISODate("2022-12-31") },
  { _id: 3, date: new ISODate("2023-01-01") }
])
```

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="isoWeek-code"></a>

`$isoWeek` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'isoWeek': { '$isoWeek': '$date' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$isoWeekYear` 연산자는 지정된 날짜에 대한 ISO 8601 주 연도 번호를 반환합니다. ISO 주 연도 수는 특히 연초와 말에 주 연도가 해당 연도와 다를 수 있다는 점에서 그레고리 역년과 다릅니다.

**파라미터**
+ `expression`: ISO 8601 주 연도 번호를 반환할 날짜 표현식입니다.

## 예제(MongoDB 쉘)
<a name="isoWeekYear-examples"></a>

이 예제에서는 `$isoWeekYear` 연산자를 사용하여 이벤트 컬렉션에 있는 각 문서의 날짜 필드에 대한 ISO 8601 주 연도를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.events.insertMany([
  { _id: 1, name: "Event 1", date: ISODate("2022-12-31T00:00:00Z") },
  { _id: 2, name: "Event 2", date: ISODate("2023-01-01T00:00:00Z") },
  { _id: 3, name: "Event 3", date: ISODate("2023-01-02T00:00:00Z") }
]);
```

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="isoWeekYear-code"></a>

`$isoWeekYear` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await events.aggregate([
    { $project: {
      name: 1,
      isoWeekYear: { $isoWeekYear: '$date' }
    }}
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(events.aggregate([
        { '$project': {
            'name': 1,
            'isoWeekYear': { '$isoWeekYear': '$date' }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$last` 연산자는 쿼리 기준과 일치하는 배열의 마지막 요소를 반환하는 데 사용됩니다. 특정 조건을 충족하는 배열에서 가장 최근 또는 마지막 요소를 검색하는 데 특히 유용합니다.

**파라미터**
+ `expression`: 배열 요소와 일치하는 표현식입니다.

## 예제(MongoDB 쉘)
<a name="last-examples"></a>

다음 예제에서는 연`$last`산자를와 함께 사용하여 특정 조건(예: 제목이 '과학')을 충족하는 배열에서 마지막 요소를 `$filter` 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  {
    "_id": 1,
    "name": "John",
    "scores": [
      { "subject": "math", "score": 82 },
      { "subject": "english", "score": 85 },
      { "subject": "science", "score": 90 }
    ]
  },
  {
    "_id": 2,
    "name": "Jane",
    "scores": [
      { "subject": "math", "score": 92 },
      { "subject": "english", "score": 88 },
      { "subject": "science", "score": 87 }
    ]
  },
  {
    "_id": 3,
    "name": "Bob",
    "scores": [
      { "subject": "math", "score": 75 },
      { "subject": "english", "score": 80 },
      { "subject": "science", "score": 85 }
    ]
  }
]);
```

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="last-code"></a>

`$last` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

def example():

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

    db = client.test
    collection = db.collection

    pipeline = [
        { "$match": { "name": "John" } },
        {
            "$project": {
                "name": 1,
                "lastScienceScore": {
                    "$last": {
                        "$filter": {
                            "input": "$scores",
                            "as": "score",
                            "cond": { "$eq": ["$$score.subject", "science"] }
                        }
                    }
                }
            }
        }
    ]

    result = list(collection.aggregate(pipeline))

    print(result)

    client.close()

example()
```

------

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

Amazon DocumentDB의 `$let` 연산자는 변수를 값에 바인딩하고 표현식에서 해당 변수를 사용하는 데 사용됩니다. 이를 통해 집계 파이프라인의 동일한 단계 내에서 후속 표현식에 사용할 수 있는 로컬 변수를 정의할 수 있습니다.

**파라미터**
+ `vars`: 표현식에 사용할 변수를 정의하는 객체입니다.
+ `in`: vars 파라미터에 정의된 변수가 사용되는 표현식입니다.

## 예제(MongoDB 쉘)
<a name="let-examples"></a>

이 예제에서는 `$let` 연산자를 사용하여 직사각형의 면적을 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="let-code"></a>

`$let` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await shapes.aggregate([
    {
      $project: {
        name: 1,
        area: {
          $let: {
            vars: {
              length: '$length',
              width: '$width'
            },
            in: {
              $multiply: ['$$length', '$$width']
            }
          }
        }
      }
    }
  ]).toArray();

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

calculateRectangleAreas();
```

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

```
from pymongo import MongoClient

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

    result = list(shapes.aggregate([
        {
            '$project': {
                'name': 1,
                'area': {
                    '$let': {
                        'vars': {
                            'length': '$length',
                            'width': '$width'
                        },
                        'in': {
                            '$multiply': ['$$length', '$$width']
                        }
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

calculate_rectangle_areas()
```

------

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

Amazon DocumentDB의 `$limit` 연산자는 쿼리에서 반환되는 문서 수를 제한하는 데 사용됩니다. MongoDB `$limit` 연산자와 비슷하지만 Amazon DocumentDB와 함께 사용할 때 몇 가지 구체적인 고려 사항이 있습니다.

Amazon DocumentDB에서 `$limit` 연산자는 일치하는 전체 문서의 하위 집합을 검색하려는 페이지 매김에 유용합니다. 이를 통해 각 응답에서 반환되는 문서 수를 제어하여 성능을 개선하고 네트워크를 통해 전송되는 데이터의 양을 줄일 수 있습니다.

**파라미터**
+ `limit`: 반환할 최대 문서 수입니다. 음수가 아닌 정수 값이어야 합니다.

## 예제(MongoDB 쉘)
<a name="limit-examples"></a>

다음 예제에서는 `$limit` 연산자를 사용하여 지정된 필터와 일치하는 최대 하나의 문서를 반환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.test.insertMany([
  { "_id": 1, "star_rating": 4, "comments": "apple is red" },
  { "_id": 2, "star_rating": 5, "comments": "comfortable couch" },
  { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" },
  { "_id": 4, "star_rating": 5, "comments": "this is a great couch" },
  { "_id": 5, "star_rating": 5, "comments": "interesting couch" }
]);
```

**쿼리 예제**

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

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

**출력**

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

## 코드 예제
<a name="limit-code"></a>

`$limit` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

      await collection.createIndex({ comments: 'text' });

      const query = {
        $and: [
          { star_rating: 5 },
          { $text: { $search: "couch" } }
        ]
      };

      const result = await collection.find(query).limit(1).toArray();

      console.log(result);

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

}

limitExample();
```

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

```
from pymongo import MongoClient

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

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

        collection.create_index([('comments', 'text')])

        query = {
            '$and': [
                {'star_rating': 5},
                {'$text': {'$search': 'couch'}}
            ]
        }

        result = collection.find(query).limit(1)

        for doc in result:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        client.close()

limit_example()
```

------

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

Amazon DocumentDB의 `$literal` 연산자는 집계 파이프라인 단계 내의 리터럴 값을 나타내는 데 사용됩니다. 필드 참조 또는 표현식으로 해석하지 않고 숫자, 문자열 또는 부울과 같은 특정 값을 포함할 수 있습니다.

이 연산자는 동적 쿼리 필터를 빌드하거나 계산을 수행할 때와 같이 보다 복잡한 집계 파이프라인의 일부로 리터럴 값을 포함해야 하는 경우에 특히 유용합니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="literal-examples"></a>

다음 예제에서는 `$literal` 연산자를 사용하여 집계 파이프라인에 리터럴 값을 포함하는 방법을 보여줍니다. 연`$literal`산자는 값 18을 \$1gt 표현식에 리터럴 값으로 포함하는 데 사용됩니다. 이렇게 하면 집계 파이프라인이 연령 필드를 리터럴 값 18과 비교하여 사람이 성인인지 확인할 수 있습니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { "name": "John Doe", "age": 30, "city": "New York" },
  { "name": "Jane Doe", "age": 25, "city": "Los Angeles" },
  { "name": "Bob Smith", "age": 35, "city": "Chicago" }
]);
```

**쿼리 예제**

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

**출력**

```
[
  {
    "_id": ObjectId("601234567890abcdef012345"),
    "name": "John Doe",
    "age": 30,
    "city": "New York",
    "isAdult": true
  },
  {
    "_id": ObjectId("601234567890abcdef012346"),
    "name": "Jane Doe",
    "age": 25,
    "city": "Los Angeles",
    "isAdult": true
  },
  {
    "_id": ObjectId("601234567890abcdef012347"),
    "name": "Bob Smith",
    "age": 35,
    "city": "Chicago",
    "isAdult": true
  }
]
```

## 코드 예제
<a name="literal-code"></a>

`$literal` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        age: 1,
        city: 1,
        isAdult: { $gt: ["$age", { $literal: 18 }] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'age': 1,
                'city': 1,
                'isAdult': { '$gt': ["$age", { '$literal': 18 }] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

버전 4.0의 새 버전입니다.

Amazon DocumentDB의 `$ln` 연산자는 지정된 숫자의 자연 로그(기본 e)를 계산합니다. 숫자의 로그를 기본 e로 반환합니다.

**파라미터**
+ `expression`: 자연 로그를 계산할 숫자입니다.

## 예제(MongoDB 쉘)
<a name="ln-examples"></a>

다음 예제에서는 `$log` 연산자를 사용하여 숫자의 자연 로그를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="ln-code"></a>

`$ln` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

    db = client.test
    collection = db.numbers

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

    print(result)
    client.close()

example()
```

------

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

버전 4.0의 새 버전입니다.

Amazon DocumentDB의 `$log` 연산자는 숫자의 자연 로그를 계산합니다. 지정된 숫자의 base-e 로그를 반환합니다.

**파라미터**
+ `expression`: 자연 로그를 계산할 숫자입니다.
+ `base`: 로그를 계산하는 기본 값입니다.

## 예제(MongoDB 쉘)
<a name="log-examples"></a>

다음 예제에서는 `$log` 연산자를 사용하여 숫자의 자연 로그를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="log-code"></a>

`$log` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

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

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        { "$project": {
            "_id": 1,
            "naturalLog": { "$log": ["$value", 10] }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

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

버전 4.0에서 새로 추가되었습니다.

Amazon DocumentDB의 `$log10` 연산자는 숫자의 base-10 로그를 계산하는 데 사용됩니다. 집계 파이프라인 내의 숫자 필드에 대한 로그 계산을 수행하는 데 유용합니다.

**파라미터**
+ `expression`: base-10 로그를 계산할 숫자 표현식입니다.

## 예제(MongoDB 쉘)
<a name="log10-examples"></a>

다음 예제에서는 `$log10` 연산자를 사용하여 숫자 필드의 base-10 로그를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="log10-code"></a>

`$log10` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

async function example() {
  let client;

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

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

    console.log(result);
  } catch (error) {
    console.error("An error occurred:", error);
  } finally {
    if (client) {
      await client.close();
    }
  }
}

example();
```

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

```
from pymongo import MongoClient

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

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

        print(result)
    
    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        if client:
            client.close()

example()
```

------

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

`$lt` 집계 연산자는 두 값을 비교하고 첫 번째 값이 두 번째 값보다 작`true`으면를 반환하고, 그렇지 않으면를 반환합니다`false`.

**파라미터**
+ `expression1`: 비교할 첫 번째 값입니다.
+ `expression2`: 비교할 두 번째 값입니다.

## 예제(MongoDB 쉘)
<a name="lt-aggregation-examples"></a>

다음 예제에서는 `$lt` 연산자를 사용하여 재고가 적은 항목을 식별하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="lt-aggregation-code"></a>

`$lt` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        stock: 1,
        lowStock: { $lt: ["$stock", 10] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'stock': 1,
                'lowStock': { '$lt': ['$stock', 10] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$lte` 집계 연산자는 두 값을 비교하고 첫 번째 값이 두 번째 값보다 작거나 같`true`으면를 반환하고, 그렇지 않으면를 반환합니다`false`.

**파라미터**
+ `expression1`: 비교할 첫 번째 값입니다.
+ `expression2`: 비교할 두 번째 값입니다.

## 예제(MongoDB 쉘)
<a name="lte-aggregation-examples"></a>

다음 예제에서는 `$lte` 연산자를 사용하여 예산 친화적인 항목을 식별하는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="lte-aggregation-code"></a>

`$lte` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        dish: 1,
        price: 1,
        affordable: { $lte: ["$price", 10] }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'dish': 1,
                'price': 1,
                'affordable': { '$lte': ['$price', 10] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$lookup` 집계 단계를 사용하면 두 컬렉션 간에 왼쪽 외부 조인을 수행할 수 있습니다. 이 작업을 사용하면 일치하는 필드 값을 기반으로 여러 컬렉션의 데이터를 결합할 수 있습니다. 관련 컬렉션의 데이터를 쿼리 결과에 통합해야 할 때 특히 유용합니다.

**파라미터**
+ `from`: 조인을 수행할 컬렉션의 이름입니다.
+ `localField`:와 일치시킬 입력 문서의 필드입니다`foreignField`.
+ `foreignField`: `from` 컬렉션에 있는 문서의 필드로,와 일치합니다`localField`.
+ `as`: `from` 컬렉션의 일치하는 문서가 포함된 출력 문서에 추가할 새 필드의 이름입니다.

## 예제(MongoDB 쉘)
<a name="lookup-examples"></a>

다음 예제에서는 `orders` 컬렉션의 데이터를 `customers` 컬렉션에 조인하는 간단한 `$lookup` 작업을 보여줍니다.

**샘플 문서 생성**

```
db.customers.insertMany([
  { _id: 1, name: "Alice" },
  { _id: 2, name: "Bob" },
  { _id: 3, name: "Charlie" }
]);

db.orders.insertMany([
  { _id: 1, customer_id: 1, total: 50 },
  { _id: 2, customer_id: 1, total: 100 },
  { _id: 3, customer_id: 2, total: 75 }
]);
```

**쿼리 예제**

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

**출력**

```
[
  {
    _id: 1,
    name: 'Alice',
    orders: [
      { _id: 2, customer_id: 1, total: 100 },
      { _id: 1, customer_id: 1, total: 50 }
    ]
  },
  { _id: 3, name: 'Charlie', orders: [] },
  {
    _id: 2,
    name: 'Bob',
    orders: [ { _id: 3, customer_id: 2, total: 75 } ]
  }
]
```

## 코드 예제
<a name="lookup-code"></a>

`$lookup` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  await client.connect();

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

  const result = await db.collection('customers').aggregate([
    {
      $lookup: {
        from: 'orders',
        localField: '_id',
        foreignField: 'customer_id',
        as: 'orders'
      }
    }
  ]).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

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

```
from pymongo import MongoClient

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

    db = client.test
    
    collection = db.customers

    pipeline = [
        {
            "$lookup": {
                "from": "orders",
                "localField": "_id",
                "foreignField": "customer_id",
                "as": "orders"
            }
        }
    ]

    result = collection.aggregate(pipeline)

    for doc in result:
        print(doc)

    client.close()

example()
```

------

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

버전 4.0의 새 버전입니다.

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$ltrim` 연산자는 문자열에서 선행 문자를 제거하는 데 사용됩니다. 기본적으로 선행 공백 문자를 제거하지만 문자 인수를 전달하여 제거할 문자 집합을 지정할 수도 있습니다.

**파라미터**
+ `input`: 선행 공백 문자를 제거할 입력 문자열입니다.
+ `chars`: (선택 사항) 특정 문자를 제거합니다.

## 예제(MongoDB 쉘)
<a name="ltrim-examples"></a>

다음 예제에서는를 사용하여 문자열의 시작 부분에서 지정된 문자(" \$1")를 제거하는 `$ltrim` 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

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

**출력**

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

## 코드 예제
<a name="ltrim-code"></a>

`$ltrim` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  try {
    await client.connect();

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

    const pipeline = [
      {
        $project: {
          _id: 0,
          name: {
            $ltrim: {
              input: '$name',
              chars: ' *'
            }
          },
          age: 1
        }
      }
    ];

    const result = await collection.aggregate(pipeline).toArray();

    console.dir(result, { depth: null });

  } finally {
    await client.close();
  }
}

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

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

```
from pymongo import MongoClient

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

        db = client.test
        collection = db.collection

        pipeline = [
            {
                "$project": {
                    "_id": 0,
                    "name": {
                        "$ltrim": {
                            "input": "$name",
                            "chars": " *"
                        }
                    },
                    "age": 1
                }
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")
    
    finally:
        client.close()

example()
```

------

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

Amazon DocumentDB의 `$map` 연산자를 사용하면 배열의 각 요소에 지정된 표현식을 적용하고 변환된 요소가 있는 새 배열을 반환할 수 있습니다. 이 연산자는 배열 내에서 데이터를 조작하고 변환하는 데 특히 유용하며, 이는 애플리케이션 코드를 단순화하고 배열 처리를 데이터베이스 수준으로 푸시하여 쿼리 성능을 개선하는 데 도움이 될 수 있습니다.

**파라미터**
+ `input`: 변환할 배열입니다.
+ `as`: (선택 사항) 처리 중인 현재 요소를 나타내는 표현식의 내에서 사용할 변수의 이름입니다.
+ `in`: 입력 배열의 각 요소에 적용할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="map-examples"></a>

다음 예제에서는 \$1map 연산자를 사용하여 숫자 배열을 변환하여 각 값을 두 배로 늘리는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { _id: 1, numbers: [1, 2, 3, 4, 5] },
  { _id: 2, numbers: [10, 20, 30, 40, 50] }
])
```

**쿼리 예제**

```
db.collection.aggregate([
  {
    $project: {
      doubledNumbers: { $map: { input: "$numbers", as: "num", in: { $multiply: ["$$num", 2] } } }
    }
  }
])
```

**출력**

```
[
  { _id: 1, doubledNumbers: [2, 4, 6, 8, 10] },
  { _id: 2, doubledNumbers: [20, 40, 60, 80, 100] }
]
```

## 코드 예제
<a name="map-code"></a>

`$map` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        doubledNumbers: { $map: { input: "$numbers", as: "num", in: { $multiply: ["$$num", 2] } } }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                'doubledNumbers': { '$map': { 'input': '$numbers', 'as': 'num', 'in': { '$multiply': ['$$num', 2] } } }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$match` 파이프라인 단계는 입력 문서를 지정된 쿼리 기준과 일치하는 문서로만 필터링하는 데 사용됩니다. 집계 작업에서 가장 일반적으로 사용되는 파이프라인 단계 중 하나입니다. `$match` 단계는 다른 파이프라인 단계보다 먼저 적용되므로 후속 단계에서 처리해야 하는 문서 수를 효율적으로 줄일 수 있습니다.

**파라미터**
+ `query`: 작업의 선택 기준을 표현하는 문서입니다. 쿼리 문서는 `find()` 메서드와 동일한 구문을 사용합니다.

## 예제(MongoDB 쉘)
<a name="match-examples"></a>

다음 예제에서는 `$match` 스테이지를 사용하여 특정 필드 값을 기반으로 문서를 필터링하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { _id: 1, name: "John", age: 25, city: "New York" },
  { _id: 2, name: "Jane", age: 30, city: "Los Angeles" },
  { _id: 3, name: "Bob", age: 35, city: "Chicago" },
  { _id: 4, name: "Alice", age: 40, city: "Miami" }
]);
```

**쿼리 예제**

```
db.collection.aggregate([
  { $match: { age: { $gt: 30 } } },
  { $project: { _id: 1, name: 1, city: 1 } }
]);
```

**출력**

```
[
  { "_id": 3, "name": "Bob", "city": "Chicago" },
  { "_id": 4, "name": "Alice", "city": "Miami" }
]
```

`$match` 단계는 `age` 필드가 30보다 큰 문서만 포함하도록 문서를 필터링합니다.

## 코드 예제
<a name="match-code"></a>

`$match` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

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

  const result = await collection.aggregate([
    { $match: { age: { $gt: 30 } } },
    { $project: { _id: 1, name: 1, city: 1 } }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        { '$match': { 'age': { '$gt': 30 } } },
        { '$project': { '_id': 1, 'name': 1, 'city': 1 } }
    ]))

    print(result)
    client.close()

example()
```

------

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

`$max` 집계 단계는 파이프라인 단계의 모든 문서에서 지정된 필드의 최대값을 반환하는 데 사용됩니다. 이 연산자는 문서 세트에서 가장 높은 값을 찾는 데 유용합니다.

**파라미터**
+ `expression`: 최대값을 계산하는 데 사용할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="max-examples"></a>

다음 예제에서는 `$max` 연산자를 사용하여 학생 문서 모음에서 최대 점수를 찾는 방법을 보여줍니다. `$group` 스테이지는 모든 문서를 그룹화하고 연`$max`산자는 모든 문서에서 `score` 필드의 최대값을 계산하는 데 사용됩니다.

**샘플 문서 생성**

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

**쿼리 예제**

```
db.students.aggregate([
  { $group: { _id: null, maxScore: { $max: "$score" } } },
  { $project: { _id: 0, maxScore: 1 } }
])
```

**출력**

```
[ { maxScore: 92 } ]
```

## 코드 예제
<a name="max-code"></a>

`$max` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await students.aggregate([
    { $group: { _id: null, maxScore: { $max: "$score" } } }
  ]).toArray();

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

findMaxScore();
```

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

```
from pymongo import MongoClient

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

    result = list(students.aggregate([
        { "$group": { "_id": None, "maxScore": { "$max": "$score" } } }
    ]))

    print(result)
    client.close()

find_max_score()
```

------

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

`$meta` 집계 연산자는 집계 파이프라인의 문서와 연결된 메타데이터에 액세스합니다. 일반적으로 텍스트 검색 점수를 검색하고 관련성을 기준으로 결과를 정렬하는 데 사용됩니다.

**파라미터**
+ `textScore`: 검색 쿼리와 문서 관련성을 나타내는 텍스트 검색 점수를 검색합니다.

## 예제(MongoDB 쉘)
<a name="meta-aggregation-examples"></a>

다음 예제에서는 집계 파이프라인에서 `$meta` 연산자를 사용하여 텍스트 검색 점수를 검색하고 정렬하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.articles.createIndex({ content: "text" });

db.articles.insertMany([
  { _id: 1, title: "Python Programming", content: "Python is a versatile programming language used for web development." },
  { _id: 2, title: "Python Guide", content: "Learn Python programming with Python tutorials and Python examples." },
  { _id: 3, title: "Java Basics", content: "Java is another popular programming language." }
]);
```

**쿼리 예제**

```
db.articles.aggregate([
  { $match: { $text: { $search: "Python" } } },
  { $addFields: { score: { $meta: "textScore" } } },
  { $sort: { score: -1 } }
]);
```

**출력**

```
[
  {
    _id: 2,
    title: 'Python Guide',
    content: 'Learn Python programming with Python tutorials and Python examples.',
    score: 1.5
  },
  {
    _id: 1,
    title: 'Python Programming',
    content: 'Python is a versatile programming language used for web development.',
    score: 0.75
  }
]
```

## 코드 예제
<a name="meta-aggregation-code"></a>

`$meta` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    { $match: { $text: { $search: "Python" } } },
    { $addFields: { score: { $meta: "textScore" } } },
    { $sort: { score: -1 } }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        { '$match': { '$text': { '$search': 'Python' } } },
        { '$addFields': { 'score': { '$meta': 'textScore' } } },
        { '$sort': { 'score': -1 } }
    ]))

    print(result)
    client.close()

example()
```

------

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

8.0에 도입

Amazon DocumentDB의 `$merge` 집계 단계는 이전 파이프라인 단계의 결과를 대상 컬렉션에 병합하는 데 사용됩니다. 이는 입력 문서의 데이터를 기반으로 대상 컬렉션에 문서를 업데이트하거나 삽입하는 데 유용합니다.

`$merge` 단계를 사용하면 입력 문서와 대상 컬렉션 간의 일치 조건에 따라 다음과 같은 다양한 작업을 수행할 수 있습니다.

```
- Insert new documents
- Update existing documents
- Delete documents
- Fail the operation if there are any conflicts
```

**파라미터**
+ `into`: (필수) 입력 문서를 병합할 대상 컬렉션의 이름입니다.
+ `on`: (필수) 입력 문서와 대상 컬렉션 간의 일치 조건으로 사용할 필드(들)입니다.
+ `whenMatched`: (선택 사항) 입력 문서가 대상 컬렉션의 기존 문서와 일치할 때 수행할 작업입니다. 지원되는 값은 `"merge"`, `"replace"`, `"keepExisting"` 및 `"fail"`입니다.
+ `whenNotMatched`: (선택 사항) 입력 문서가 대상 컬렉션의 문서와 일치하지 않을 때 수행할 작업입니다. 지원되는 값은 `"insert"` 및 입니다`"fail"`.

## 예제(MongoDB 쉘)
<a name="merge-examples"></a>

다음 예제에서는 `$merge` 스테이지를 사용하여 입력 파이프라인의 새 데이터로 `users` 컬렉션을 업데이트하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { _id: 1, name: "John Doe", email: "john@example.com" },
  { _id: 2, name: "Jane Smith", email: "jane@example.com" }
]);

db.inputData.insertMany([
  { _id: 1, name: "John Doe", email: "john@example.com", phone: "123-456-7890" },
  { _id: 3, name: "Bob Johnson", email: "bob@example.com", phone: "987-654-3210" }
]);
```

**쿼리 예제**

```
db.inputData.aggregate([
  {
    $merge: {
      into: "users",
      on: "_id",
      whenMatched: "merge",
      whenNotMatched: "insert"
    }
  }
])
```

**출력**

`$merge` 파이프라인을 실행한 후 `users` 컬렉션에는 다음 문서가 포함됩니다.

```
[
  { _id: 1, name: "John Doe", email: "john@example.com", phone: "123-456-7890" },
  { _id: 2, name: "Jane Smith", email: "jane@example.com" },
  { _id: 3, name: "Bob Johnson", email: "bob@example.com", phone: "987-654-3210" }
]
```

## 코드 예제
<a name="merge-code"></a>

`$merge` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

다음은 Node.js 애플리케이션에서 \$1merge 연산자를 사용하는 예입니다.

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

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

  await db.collection('inputData').aggregate([
    {
      $merge: {
        into: 'users',
        on: '_id',
        whenMatched: 'merge',
        whenNotMatched: 'insert'
      }
    }
  ]).toArray();

  const users = await db.collection('users').find({}).toArray();
  console.log(users);

  await client.close();
}

example();
```

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

다음은 Python 애플리케이션에서 \$1merge 연산자를 사용하는 예입니다.

```
from pymongo import MongoClient

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

    # Assumes collections 'users' and 'inputData' already exist with sample data
    db.inputData.aggregate([
        {
            '$merge': {
                'into': 'users',
                'on': '_id',
                'whenMatched': 'merge',
                'whenNotMatched': 'insert'
            }
        }
    ])

    users = list(db.users.find({}))
    print(users)

    client.close()

example()
```

------

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

Amazon DocumentDB의 `$mergeObjects` 연산자는 여러 문서 또는 객체를 단일 문서로 결합하는 데 사용됩니다. 이 연산자는 두 개 이상의 문서 또는 객체의 내용을 병합해야 할 때 특히 유용하며, 한 객체의 값을 다른 객체의 값으로 덮어쓸 수 있습니다.

**파라미터**
+ `expression1`: 병합할 첫 번째 객체입니다.
+ `expression2`: (선택 사항) 병합할 두 번째 객체입니다.
+ `expression3`: (선택 사항) 병합할 추가 객체입니다.

## 예제(MongoDB 쉘)
<a name="mergeObjects-examples"></a>

다음 예제에서는 `$mergeObjects` 연산자를 사용하여 두 객체를 결합하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { "_id": 1, "name": "John", "address": { "city": "New York", "state": "NY" } },
  { "_id": 2, "name": "Jane", "address": { "city": "Los Angeles", "state": "CA" } }
]);
```

**쿼리 예제**

```
db.collection.aggregate([
  {
    $project: {
      "combinedAddress": {
        $mergeObjects: ["$address", { "country": "USA" }]
      }
    }
  }
])
```

**출력**

```
[
  {
    "_id": 1,
    "combinedAddress": {
      "city": "New York",
      "state": "NY",
      "country": "USA"
    }
  },
  {
    "_id": 2,
    "combinedAddress": {
      "city": "Los Angeles",
      "state": "CA",
      "country": "USA"
    }
  }
]
```

## 코드 예제
<a name="mergeObjects-code"></a>

`$mergeObjects` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await collection.aggregate([
    {
      $project: {
        "combinedAddress": {
          $mergeObjects: ["$address", { "country": "USA" }]
        }
      }
    }
  ]).toArray();

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

example();
```

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

```
from pymongo import MongoClient

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

    result = list(collection.aggregate([
        {
            '$project': {
                "combinedAddress": {
                    "$mergeObjects": ["$address", { "country": "USA" }]
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

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

Amazon DocumentDB의 `$millisecond` 연산자는 날짜 값의 밀리초 부분을 추출하는 데 사용됩니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="millisecond-examples"></a>

이 예제에서는 `$millisecond` 연산자를 사용하여 날짜 값의 밀리초 부분을 추출하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.events.insert([
  {
    "name": "Event 1",
    "timestamp": ISODate("2023-04-21T10:30:15.123Z")
  },
  {
    "name": "Event 2",
    "timestamp": ISODate("2023-04-21T10:30:15.456Z")
  },
  {
    "name": "Event 3",
    "timestamp": ISODate("2023-04-21T10:30:15.789Z")
  }
])
```

**쿼리 예제**

```
db.events.aggregate([
  {
    $project: {
      name: 1,
      milliseconds: { $millisecond: "$timestamp" }
    }
  }
])
```

**출력**

```
[
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c1"),
    "name": "Event 1",
    "milliseconds": 123
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c2"),
    "name": "Event 2",
    "milliseconds": 456
  },
  {
    "_id": ObjectId("644332a42054ed1b0d15f0c3"),
    "name": "Event 3",
    "milliseconds": 789
  }
]
```

## 코드 예제
<a name="millisecond-code"></a>

`$millisecond` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await events.aggregate([
    {
      $project: {
        name: 1,
        milliseconds: { $millisecond: '$timestamp' }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient

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

result = list(events.aggregate([
    {
        '$project': {
            'name': 1,
            'milliseconds': { '$millisecond': '$timestamp' }
        }
    }
]))

print(result)

client.close()
```

------

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

연`$min`산자는 값 배열에서 최소값을 반환합니다. 집계 단계에서 여러 문서에서 지정된 필드의 최소값을 찾는 데 사용할 수 있습니다.

**파라미터**
+ `expression`: 평가할 표현식입니다. 필드 경로, 변수 또는 값으로 확인되는 표현식일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="min-examples"></a>

다음 예제에서는 연`$min`산자를 사용하여 여러 문서에서 `age` 필드의 최소값을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

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

**쿼리 예제**

```
db.users.aggregate([
  { $group: { _id: null, minAge: { $min: "$age" } } },
  { $project: { _id: 0, minAge: 1 } }
])
```

**출력**

```
[ { minAge: 28 } ]
```

## 코드 예제
<a name="min-code"></a>

`$min` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

async function findMinAge() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([
    { $group: {
        _id: null,
        minAge: { $min: "$age" }
      }}
  ]).toArray();

  console.log(result);
  client.close();
}

findMinAge();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_min_age():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db.users

    result = list(users.aggregate([
        { "$group": {
            "_id": None,
            "minAge": { "$min": "$age" }
        }}
    ]))

    print(result)
    client.close()

find_min_age()
```

------

# \$1minute
<a name="minute"></a>

Amazon DocumentDB의 `$minute` 집계 파이프라인 단계는 날짜 또는 타임스탬프 필드에서 분 값을 추출합니다.

이 연산자는 집계 파이프라인 내에서 날짜 및 시간 기반 계산 또는 그룹화를 수행해야 할 때 유용합니다.

**파라미터**
+ `expression`: 분 값을 추출할 날짜 또는 타임스탬프 필드입니다.

## 예제(MongoDB 쉘)
<a name="minute-examples"></a>

다음 예제에서는 `$minute` 연산자를 사용하여 타임스탬프 필드에서 추출한 분 값을 기준으로 문서를 그룹화하고 각 그룹의 문서 수를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.events.insertMany([
  { timestamp: new Date("2023-04-15T10:30:25.000Z") },
  { timestamp: new Date("2023-04-15T10:30:35.000Z") },
  { timestamp: new Date("2023-04-15T10:31:05.000Z") },
  { timestamp: new Date("2023-04-15T10:31:45.000Z") },
  { timestamp: new Date("2023-04-15T10:32:15.000Z") }
]);
```

**쿼리 예제**

```
db.events.aggregate([
  {
    $group: {
      _id: {
        minute: { $minute: "$timestamp" }
      },
      count: { $count: {} }
    }
  },
  { $sort: { "_id.minute": 1 } }
]);
```

**출력**

```
[
  { "_id": { "minute": 30 }, "count": 2 },
  { "_id": { "minute": 31 }, "count": 2 },
  { "_id": { "minute": 32 }, "count": 1 }
]
```

## 코드 예제
<a name="minute-code"></a>

`$minute` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  await collection.insertMany([
    { timestamp: new Date("2023-04-15T10:30:25.000Z") },
    { timestamp: new Date("2023-04-15T10:30:35.000Z") },
    { timestamp: new Date("2023-04-15T10:31:05.000Z") },
    { timestamp: new Date("2023-04-15T10:31:45.000Z") },
    { timestamp: new Date("2023-04-15T10:32:15.000Z") }
  ]);

  const result = await collection.aggregate([
    {
      $group: {
        _id: {
          minute: { $minute: "$timestamp" }
        },
        count: { $count: {} }
      }
    },
    { $sort: { "_id.minute": 1 } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from datetime import datetime

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    collection.insert_many([
        {'timestamp': datetime(2023, 4, 15, 10, 30, 25)},
        {'timestamp': datetime(2023, 4, 15, 10, 30, 35)},
        {'timestamp': datetime(2023, 4, 15, 10, 31, 5)},
        {'timestamp': datetime(2023, 4, 15, 10, 31, 45)},
        {'timestamp': datetime(2023, 4, 15, 10, 32, 15)}
    ])

    result = list(collection.aggregate([
        {
            '$group': {
                '_id': {
                    'minute': {'$minute': '$timestamp'}
                },
                'count': {'$count': {}}
            }
        },
        {'$sort': {'_id.minute': 1}}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1mod
<a name="mod"></a>

연`$mod`산자는 숫자에 모듈로 연산을 수행하는 산술 연산자입니다. 한 숫자를 다른 숫자로 나눈 나머지 부분을 반환합니다. 이 연산자는 일반적으로 숫자가 홀수인지 짝수인지 확인하거나 항목을 한정된 수의 그룹으로 분산하는 데 사용됩니다.

**파라미터**
+ `expression1`: 배당 표현식입니다.
+ `expression2`: 디바이저 표현식입니다.

## 예제(MongoDB 쉘)
<a name="mod-examples"></a>

이 예제에서는 연`$mod`산자를 사용하여 100개 패키지로 배송할 때 남은 위젯 수를 확인하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.widgets.insertMany([
  { "_id" : 1, "widget" : "A", "count" : 80372 },
  { "_id" : 2, "widget" : "B", "count" : 409282 },
  { "_id" : 3, "widget" : "C", "count" : 60739 }
])
```

**쿼리 예제**

```
db.widgets.aggregate([
  { $addFields: { leftOver: { $mod: [ "$count", 100 ] } } }
])
```

**출력**

```
[
  { "_id" : 1, "widget" : "A", "count" : 80372, "leftOver" : 72 },
  { "_id" : 2, "widget" : "B", "count" : 409282, "leftOver" : 82 },
  { "_id" : 3, "widget" : "C", "count" : 60739, "leftOver" : 39 }
]
```

출력에는의 나머지 부분을 각 문서에 대해 100으로 `count` 나눈 값이 표시되며, 이는 100개 패키지로 배송할 때 남은 위젯 수를 나타냅니다.

## 코드 예제
<a name="mod-code"></a>

`$mod` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const widgets = db.collection('widgets');

  await widgets.insertMany([
    { "_id" : 1, "widget" : "A", "count" : 80372 },
    { "_id" : 2, "widget" : "B", "count" : 409282 },
    { "_id" : 3, "widget" : "C", "count" : 60739 }
  ]);

  const result = await widgets.aggregate([
    { $addFields: { leftOver: { $mod: [ "$count", 100 ] } } }
  ]).toArray();

  console.log(result);
  client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
widgets = db['widgets']

widgets.insert_many([
    { "_id" : 1, "widget" : "A", "count" : 80372 },
    { "_id" : 2, "widget" : "B", "count" : 409282 },
    { "_id" : 3, "widget" : "C", "count" : 60739 }
])

result = list(widgets.aggregate([
    { "$addFields": { "leftOver": { "$mod": [ "$count", 100 ] } } }
]))

print(result)
client.close()
```

------

# \$1month
<a name="month"></a>

Amazon DocumentDB의 `$month` 연산자는 날짜의 월을 1에서 12 사이의 숫자로 반환합니다. 이 연산자는 날짜 필드에서 월 구성 요소를 추출하고 날짜 기반 집계 및 분석을 수행하는 데 유용합니다.

**파라미터**
+ `date_expression`: 월을 추출하려는 날짜 또는 타임스탬프가 포함된 표현식 또는 필드입니다.

## 예제(MongoDB 쉘)
<a name="month-examples"></a>

다음 예제에서는 `$month` 연산자를 사용하여 날짜 필드에서 월을 추출하고 데이터를 월별로 그룹화하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.sales.insert([
  { product: "abc123", price: 10.99, date: new Date("2022-01-15") },
  { product: "def456", price: 15.50, date: new Date("2022-02-28") },
  { product: "ghi789", price: 8.25, date: new Date("2022-03-10") },
  { product: "jkl012", price: 12.75, date: new Date("2022-04-05") },
  { product: "mno345", price: 18.99, date: new Date("2022-05-20") }
]);
```

**쿼리 예제**

```
db.sales.aggregate([
  { $group: { 
      _id: { month: { $month: "$date" } },
      totalSales: { $sum: "$price" }
    }},
  { $sort: { "_id.month": 1 } }
]);
```

**출력**

```
[
  { _id: { month: 1 }, totalSales: 10.99 },
  { _id: { month: 2 }, totalSales: 15.5 },
  { _id: { month: 3 }, totalSales: 8.25 },
  { _id: { month: 4 }, totalSales: 12.75 },
  { _id: { month: 5 }, totalSales: 18.99 }
]
```

## 코드 예제
<a name="month-code"></a>

`$month` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function groupSalesByMonth() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();
    const db = client.db('test');
    const collection = db.collection('sales');

    const pipeline = [
      {
        $group: {
          _id: { month: { $month: "$date" } },
          totalSales: { $sum: "$price" }
        }
      },
      {
        $sort: { "_id.month": 1 }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();

    console.dir(results, { depth: null });

  } finally {
    await client.close();
  }
}

groupSalesByMonth().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def group_sales_by_month():
  
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    try:
        db = client.test
        collection = db.sales

        pipeline = [
            {
                "$group": {
                    "_id": { "$month": "$date" }, 
                    "totalSales": { "$sum": "$price" }  
                }
            },
            {
                "$sort": { "_id": 1 } 
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        client.close()

group_sales_by_month()
```

------

# \$1multiply
<a name="multiply"></a>

Amazon DocumentDB의 `$multiply` 연산자는 둘 이상의 필드 또는 표현식 값을 곱하는 데 사용됩니다. 이 연산자는 문서 내의 숫자 필드에 산술 연산을 수행하는 데 특히 유용합니다. `$project` 및와 같은 집계 파이프라인의 다양한 단계에서 사용하여 새 필드를 `$addFields`생성하거나 기존 필드를 수정할 수 있습니다.

**파라미터**
+ `expression1`: 곱할 첫 번째 숫자 표현식입니다.
+ `expression2`: 곱할 두 번째 숫자 표현식입니다.
+ `[expression3, ...]`: (선택 사항) 곱할 추가 숫자 표현식입니다.

## 예제(MongoDB 쉘)
<a name="multiply-examples"></a>

다음 예제에서는 `$multiply`를 사용하여를 곱`bonus_miles`하고 여정`base_miles``bonus_rate`에 신용 카드를 사용한 고객을 계산하는 방법을 보여줍니다.

**샘플 문서**

```
db.miles.insertMany([
{ "_id": 1, "customer_name": "Arnav Desai", "member_since": ISODate("1997-03-01T00:00:00Z"), "base_miles": 2500, "bonus_rate": 1.8, "credit_card": true, "trip_cost": 250 },
{ "_id": 2, "customer_name": "Jorge Souza", "member_since": ISODate("2004-01-10T00:00:00Z"), "base_miles": 1890, "bonus_rate": 1.4, "credit_card": true, "trip_cost": 189 },
{ "_id": 3, "customer_name": "Saanvi Sarkar", "member_since": ISODate("1999-11-22T00:00:00Z"), "base_miles": 3250, "bonus_rate": 1.8, "credit_card": false, "trip_cost": 325 },
{ "_id": 4, "customer_name": "Paulo Santos", "member_since": ISODate("2021-06-19T00:00:00Z"), "base_miles": 2980, "bonus_rate": 1.2, "credit_card": true, "trip_cost": 298 },
{ "_id": 5, "customer_name": "Wang Xiulan", "member_since": ISODate("1995-12-04T00:00:00Z"), "base_miles": 1350, "bonus_rate": 1.9, "credit_card": false, "trip_cost": 135 }
]);
```

**쿼리 예제**

```
db.miles.aggregate([
  {
    $match: { credit_card: true }
  },
  {
    $project: {
      customer_name: 1,
      base_miles: 1,
      bonus_rate:1,
      credit_card: 1,
      total_miles: {
        $multiply: ["$base_miles", "$bonus_rate"]
      }
    }
  }
]);
```

**출력**

```
[
  { _id: 1, customer_name: 'Arnav Desai', base_miles: 12500, bonus_rate: 1.8, credit_card: true, total_miles: 22500 },
  { _id: 3, customer_name: 'Saanvi Sarkar',base_miles: 15200, bonus_rate: 1.8, credit_card: true, total_miles: 27360 },
  { _id: 4, customer_name: 'Paulo Santos', base_miles: 3400, bonus_rate: 1.1, credit_card: true, total_miles: 3740 }
]
```

## 코드 예제
<a name="multiply-code"></a>

`$multiply` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function multiplyBonusMiles() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  const result = await collection.aggregate([
    { $match: { credit_card: true } },
    {
      $project: {
        customer_name: 1,
        base_miles: 1,
        bonus_rate: 1,
        credit_card: 1,
        total_miles: {
          $multiply: ["$base_miles", "$bonus_rate"]
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

multiplyBonusMiles();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def multiply_bonus_miles():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['miles']

    result = list(collection.aggregate([
        {'$match': {'credit_card': True}},
        {
            '$project': {
                'customer_name': 1,
                'base_miles': 1,
                'bonus_rate': 1,
                'credit_card': 1,
                'total_miles': {
                    '$multiply': ['$base_miles', '$bonus_rate']
                }
            }
        }
    ]))

    print(result)
    client.close()

multiply_bonus_miles()
```

------

# \$1natural
<a name="natural"></a>

Amazon DocumentDB의 `$natural` 연산자는 문서를 컬렉션에 삽입한 순서인 자연 순서로 정렬하는 데 사용됩니다. 이는 지정된 필드의 값을 기반으로 문서를 정렬하는 기본 정렬 동작과는 대조적입니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="natural-examples"></a>

다음 예제에서는 `$natural` 연산자를 사용하여 컬렉션의 문서를 자연 순서로 정렬하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "_id": 1, "name": "María García", "age": 28 },
  { "_id": 2, "name": "Arnav Desai", "age": 32 },
  { "_id": 3, "name": "Li Juan", "age": 25 },
  { "_id": 4, "name": "Carlos Salazar", "age": 41 },
  { "_id": 5, "name": "Sofia Martínez", "age": 35 }
]);
```

**쿼리 예제**

```
db.people.find({}, { "_id": 1, "name": 1 }).sort({ "$natural": 1 });
```

**출력**

```
[
  { "_id": 1, "name": "María García" },
  { "_id": 2, "name": "Arnav Desai" },
  { "_id": 3, "name": "Li Juan" },
  { "_id": 4, "name": "Carlos Salazar" },
  { "_id": 5, "name": "Sofia Martínez" }
]
```

쿼리는 모음의 문서를 삽입된 순서인 자연 순서로 정렬합니다.

## 코드 예제
<a name="natural-code"></a>

`$natural` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const documents = await collection.find({}, { projection: { _id: 1, name: 1 } })
    .sort({ $natural: 1 })
    .toArray();

  console.log(documents);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']

    documents = list(collection.find({}, {'_id': 1, 'name': 1}).sort('$natural', 1))
    print(documents)

    client.close()

example()
```

------

# \$1ne
<a name="ne-aggregation"></a>

`$ne` 집계 연산자는 두 값을 비교하고 값이 같`true`지 않으면를 반환하고 그렇지 않으면를 반환합니다`false`.

**파라미터**
+ `expression1`: 비교할 첫 번째 값입니다.
+ `expression2`: 비교할 두 번째 값입니다.

## 예제(MongoDB 쉘)
<a name="ne-aggregation-examples"></a>

다음 예제에서는 `$ne` 연산자를 사용하여 상태 변경이 있는 주문을 식별하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.orders.insertMany([
  { _id: 1, orderId: "A123", status: "shipped", expectedStatus: "shipped" },
  { _id: 2, orderId: "B456", status: "pending", expectedStatus: "shipped" },
  { _id: 3, orderId: "C789", status: "delivered", expectedStatus: "delivered" }
]);
```

**쿼리 예제**

```
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      status: 1,
      expectedStatus: 1,
      needsAttention: { $ne: ["$status", "$expectedStatus"] }
    }
  }
]);
```

**출력**

```
[
  { _id: 1, orderId: 'A123', status: 'shipped', expectedStatus: 'shipped', needsAttention: false },
  { _id: 2, orderId: 'B456', status: 'pending', expectedStatus: 'shipped', needsAttention: true },
  { _id: 3, orderId: 'C789', status: 'delivered', expectedStatus: 'delivered', needsAttention: false }
]
```

## 코드 예제
<a name="ne-aggregation-code"></a>

`$ne` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $project: {
        orderId: 1,
        status: 1,
        expectedStatus: 1,
        needsAttention: { $ne: ["$status", "$expectedStatus"] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.aggregate([
        {
            '$project': {
                'orderId': 1,
                'status': 1,
                'expectedStatus': 1,
                'needsAttention': { '$ne': ['$status', '$expectedStatus'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1not
<a name="not-aggregation"></a>

`$not` 집계 연산자는 표현식에 대해 논리적 NOT 작업을 수행합니다. 표현식이 로 평가`true`되면 `false`를 반환하고 표현식이 로 평가`false`되면를 반환합니다`true`.

**파라미터**
+ `expression`: 부정할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="not-aggregation-examples"></a>

다음 예제에서는 `$not` 연산자를 사용하여 부울 값을 반전하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { _id: 1, name: "Alice", active: true },
  { _id: 2, name: "Bob", active: false },
  { _id: 3, name: "Charlie", active: true }
]);
```

**쿼리 예제**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      active: 1,
      inactive: { $not: ["$active"] }
    }
  }
]);
```

**출력**

```
[
  { _id: 1, name: 'Alice', active: true, inactive: false },
  { _id: 2, name: 'Bob', active: false, inactive: true },
  { _id: 3, name: 'Charlie', active: true, inactive: false }
]
```

## 코드 예제
<a name="not-aggregation-code"></a>

`$not` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        active: 1,
        inactive: { $not: ["$active"] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'active': 1,
                'inactive': { '$not': ['$active'] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1objectToArray
<a name="objectToArray"></a>

Amazon DocumentDB의 `$objectToArray` 집계 연산자는 객체(또는 문서)를 배열로 변환합니다. 연산자에 대한 입력은 문서이며 출력은 입력 문서의 각 필드-값 페어에 대한 배열 요소로 구성됩니다. 이 연산자는 특정 필드의 최대값 또는 최소값이 있는 문서를 찾으려는 경우와 같이 문서의 개별 필드를 배열로 사용해야 할 때 유용합니다.

**파라미터**
+ `expression`: 배열로 변환할 문서 표현식입니다.

## 예제(MongoDB 쉘)
<a name="objectToArray-examples"></a>

다음 예제에서는 `$objectToArray` 운영자를 사용하여 비디오 렌탈 스토어 체인의 최대 인벤토리가 있는 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.videos.insertMany([
  {
    "_id": 1,
    "name": "Live Soft",
    "inventory": {
      "Des Moines": 1000,
      "Ames": 500
    }
  },
  {
    "_id": 2,
    "name": "Top Pilot",
    "inventory": {
      "Mason City": 250,
      "Des Moines": 1000
    }
  },
  {
    "_id": 3,
    "name": "Romancing the Rock",
    "inventory": {
      "Mason City": 250,
      "Ames": 500
    }
  },
  {
    "_id": 4,
    "name": "Bravemind",
    "inventory": {
      "Mason City": 250,
      "Des Moines": 1000,
      "Ames": 500
    }
  }
]);
```

**쿼리 예제**

```
db.videos.aggregate([
  {
    $project: {
      name: 1,
      videos: {
        $objectToArray: "$inventory"
      }
    }
  },
  {
    $unwind: "$videos"
  },
  {
    $group: {
      _id: "$name",
      maxInventory: {
        $max: "$videos.v"
      }
    }
  }
]);
```

**출력**

```
[
  {
    "_id": "Bravemind",
    "maxInventory": 1000
  },
  {
    "_id": "Live Soft",
    "maxInventory": 1000
  },
  {
    "_id": "Romancing the Rock",
    "maxInventory": 500
  },
  {
    "_id": "Top Pilot",
    "maxInventory": 1000
  }
]
```

## 코드 예제
<a name="objectToArray-code"></a>

`$objectToArray` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findMaxInventory() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const videos = db.collection('videos');

  const result = await videos.aggregate([
    {
      $project: {
        name: 1,
        videos: {
          $objectToArray: "$inventory"
        }
      }
    },
    {
      $unwind: "$videos"
    },
    {
      $group: {
        _id: "$name",
        maxInventory: {
          $max: "$videos.v"
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

findMaxInventory();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_max_inventory():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    videos = db['videos']

    result = list(videos.aggregate([
        {
            '$project': {
                'name': 1,
                'videos': {
                    '$objectToArray': '$inventory'
                }
            }
        },
        {
            '$unwind': '$videos'
        },
        {
            '$group': {
                '_id': '$name',
                'maxInventory': {
                    '$max': '$videos.v'
                }
            }
        }
    ]))

    print(result)
    client.close()

find_max_inventory()
```

------

# \$1or
<a name="or-aggregation"></a>

`$or` 집계 연산자는 여러 표현식을 평가하고 하나 이상의 표현식이 로 평가`true`되면를 반환합니다`true`. 모든 표현식이 인 `false` 경우에만 반환됩니다`false`.

**파라미터**
+ `expressions`: 평가할 표현식의 배열입니다.

## 예제(MongoDB 쉘)
<a name="or-aggregation-examples"></a>

다음 예제에서는 `$or` 연산자를 사용하여 제품이 여러 기준 중 하나를 충족하는지 확인하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.items.insertMany([
  { _id: 1, name: "Widget", price: 150, onSale: false },
  { _id: 2, name: "Gadget", price: 45, onSale: false },
  { _id: 3, name: "Tool", price: 200, onSale: true }
]);
```

**쿼리 예제**

```
db.items.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      onSale: 1,
      goodDeal: {
        $or: [
          { $lt: ["$price", 50] },
          { $eq: ["$onSale", true] }
        ]
      }
    }
  }
]);
```

**출력**

```
[
  { _id: 1, name: 'Widget', price: 150, onSale: false, goodDeal: false },
  { _id: 2, name: 'Gadget', price: 45, onSale: false, goodDeal: true },
  { _id: 3, name: 'Tool', price: 200, onSale: true, goodDeal: true }
]
```

## 코드 예제
<a name="or-aggregation-code"></a>

`$or` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('items');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        price: 1,
        onSale: 1,
        goodDeal: {
          $or: [
            { $lt: ["$price", 50] },
            { $eq: ["$onSale", true] }
          ]
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['items']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'price': 1,
                'onSale': 1,
                'goodDeal': {
                    '$or': [
                        { '$lt': ['$price', 50] },
                        { '$eq': ['$onSale', True] }
                    ]
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1out
<a name="out"></a>

Amazon DocumentDB의 `$out` 연산자는 집계 파이프라인의 결과를 지정된 컬렉션에 쓰는 데 사용됩니다.

`$out`는 파이프라인의 마지막 단계여야 합니다.

**파라미터**
+ `output_collection`: 집계 결과를 쓸 출력 컬렉션의 이름입니다.

**참고**: 컬렉션이 이미 있는 경우 집계 단계의 결과로 대체됩니다.

## 예제(MongoDB 쉘)
<a name="out-examples"></a>

다음 예제에서는 Amazon DocumentDB의 `$out` 연산자를 사용하여 집계 파이프라인의 결과를 새 컬렉션에 쓰는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertMany([
  { _id: 1, name: "Wireless Headphones", category: "Electronics", price: 100.0 },
  { _id: 2, name: "Smartphone", category: "Electronics", price: 200.0 },
  { _id: 3, name: "JavaScript Guide", category: "Books", price: 50.0 },
  { _id: 4, name: "Database Design Handbook", category: "Books", price: 75.0 }
]);
```

**쿼리 예제**

```
db.products.aggregate([
  { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
  { $out: "product_categories" }
])
```

**출력**

없음(결과가 출력 컬렉션에 기록됨).

집계 파이프라인은 제품을 범주별로 그룹화하고 각 범주에 대한 항목의 총 가격을 계산합니다. 연`$out`산자는 "product\$1categories"라는 새 컬렉션에 결과를 기록합니다.

**출력 컬렉션의 결과를 보려면:**

```
db.product_categories.find()
[
{ "_id" : "Books", "totalPrice" : 125 },
{ "_id" : "Electronics", "totalPrice" : 300 }
]
```

## 코드 예제
<a name="out-code"></a>

`$out` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function demo_out_operator() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const products = db.collection('products');

  // Execute aggregation with $out - results are stored in 'product_categories' collection
  await products.aggregate([
    { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
    { $out: "product_categories" }
  ]).toArray();

  // Retrieve the results from the output collection (limited to 20 records)
  const productCategories = db.collection('product_categories');
  const results = await productCategories.find({}).limit(20).toArray();
  
  console.log('Results stored in product_categories collection:', results);
  await client.close();
}

demo_out_operator();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def demo_out_operator():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    products = db['products']

    # Execute aggregation with $out - results are stored in 'product_categories' collection
    list(products.aggregate([
        { '$group': { '_id': '$category', 'totalPrice': { '$sum': '$price' } } },
        { '$out': 'product_categories' }
    ]))

    # Retrieve the results from the output collection (limited to 20 records)
    product_categories = db['product_categories']
    results = list(product_categories.find({}).limit(20))
    
    print('Results stored in product_categories collection:', results)
    client.close()

demo_out_operator()
```

------

# \$1pow
<a name="pow"></a>

8.0에 도입

Amazon DocumentDB의 `$pow` 연산자를 사용하면 숫자를 출력으로 높일 수 있습니다. 이는 집계 파이프라인 내에서 지수 계산을 수행하는 데 유용할 수 있습니다.

**파라미터**
+ `<number>` (필수): 전원으로 높일 숫자입니다.
+ `<exponent>` (필수): 숫자를 늘려야 하는 힘입니다.

## 예제(MongoDB 쉘)
<a name="pow-examples"></a>

다음 예제에서는 `$pow` 연산자를 사용하여 숫자의 제곱을 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.numbers.insertMany([
  { "_id": 1, "value": 2 },
  { "_id": 2, "value": 3 },
  { "_id": 3, "value": 4 }
]);
```

**쿼리 예제**

```
db.numbers.aggregate([
  { $addFields: { "square": { $pow: ["$value", 2] } } }
])
```

**출력**

```
[
  { "_id": 1, "value": 2, "square": 4 },
  { "_id": 2, "value": 3, "square": 9 },
  { "_id": 3, "value": 4, "square": 16 }
]
```

## 코드 예제
<a name="pow-code"></a>

`$pow` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

다음은 Node.js 애플리케이션에서 \$1pow 연산자를 사용하는 예입니다.

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $addFields: { "square": { $pow: ["$value", 2] } } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

다음은 Python 애플리케이션에서 \$1pow 연산자를 사용하는 예입니다.

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        { "$addFields": { "square": { "$pow": ["$value", 2] } } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1push
<a name="push-aggregation"></a>

`$push` 집계 연산자는 각 그룹의 지정된 표현식에서 모든 값의 배열을 반환합니다. 일반적으로 `$group` 스테이지 내에서 값을 배열에 누적하는 데 사용됩니다.

**파라미터**
+ `expression`: 그룹의 각 문서에 대해 평가할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="push-aggregation-examples"></a>

다음 예제에서는 `$push` 연산자를 사용하여 각 범주에 대한 모든 제품 이름을 수집하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.sales.insertMany([
  { _id: 1, category: "Electronics", product: "Laptop", amount: 1200 },
  { _id: 2, category: "Electronics", product: "Mouse", amount: 25 },
  { _id: 3, category: "Furniture", product: "Desk", amount: 350 },
  { _id: 4, category: "Furniture", product: "Chair", amount: 150 },
  { _id: 5, category: "Electronics", product: "Keyboard", amount: 75 }
]);
```

**쿼리 예제**

```
db.sales.aggregate([
  {
    $group: {
      _id: "$category",
      products: { $push: "$product" }
    }
  }
]);
```

**출력**

```
[
  { _id: 'Furniture', products: [ 'Desk', 'Chair' ] },
  { _id: 'Electronics', products: [ 'Laptop', 'Mouse', 'Keyboard' ] }
]
```

## 코드 예제
<a name="push-aggregation-code"></a>

`$push` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('sales');

  const result = await collection.aggregate([
    {
      $group: {
        _id: "$category",
        products: { $push: "$product" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['sales']

    result = list(collection.aggregate([
        {
            '$group': {
                '_id': '$category',
                'products': { '$push': '$product' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1project
<a name="project"></a>

Amazon DocumentDB의 `$project` 연산자를 사용하면 출력 문서에서 필드를 선택적으로 포함하거나 제외하고, 값을 다음 파이프라인 단계에 전달하고, 입력 문서 값에서 새 필드를 계산할 수 있습니다.

**파라미터**
+ `field`: 출력 문서에서 포함하거나 제외할 필드로, 필드 경로(예: "a.b.c")일 수 있습니다.
+ `1` 또는 `true`: 출력에 필드를 포함합니다.
+ `0` 또는 `false`: 출력에서 필드를 제외합니다.

## 예제(MongoDB 쉘)
<a name="project-examples"></a>

다음 예제에서는 학생 컬렉션에서 `$project` 연산자의 사용을 보여줍니다.

**샘플 문서 생성**

```
db.students.insertMany([
  { "_id": 1, "name": "Alejandro Rosalez", "math": 85, "science": 92, "grade": "A" },
  { "_id": 2, "name": "Carlos Salazar", "math": 78, "science": 84, "grade": "B" },
  { "_id": 3, "name": "Nikhil Jayashankar", "math": 95, "science": 89, "grade": "A" },
  { "_id": 4, "name": "Shirley Rodriguez", "math": 72, "science": 76, "grade": "B" }
  ]);
```

이 쿼리에는 출력에 `name` 및 `math` 필드만 포함됩니다. 명시적으로 제외되지 않는 한 `_id` 필드는 기본적으로 포함됩니다.

```
db.students.aggregate([
  { $project: { "name": 1, "math": 1 } }
])
```

**출력**

```
{ _id: 1, name: "Alejandro Rosalez", math: 85 }
{ _id: 2, name: "Carlos Salazar", math: 78 }
{ _id: 3, name: "Nikhil Jayashankar", math: 95 }
{ _id: 4, name: "Shirley Rodriguez", math: 72 }
```

이 쿼리는 출력에서 `grade` 및 `_id` 필드를 제외하여 다른 모든 필드(, `name`, `math``science`)를 표시합니다.

```
db.students.aggregate([
  { $project: { "grade": 0, "_id": 0 } }
])
```

**출력**

```
{ name: "Alejandro Rosalez", math: 85, science: 92 }
{ name: "Carlos Salazar", math: 78, science: 84 }
{ name: "Nikhil Jayashankar", math: 95, science: 89 }
{ name: "Shirley Rodriguez", math: 72, science: 76 }
```

## 코드 예제
<a name="project-code"></a>

`$project` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  const result = await collection.aggregate([
    { $project: { "name": 1, "math": 1 } }
  ]).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['students']

    result = list(collection.aggregate([
        { '$project': { 'name': 1, 'math': 1 } }
    ]))
    print(result)

    client.close()

example()
```

------

# \$1rand
<a name="rand"></a>

버전 8.0의 새로운 기능

Amazon DocumentDB의 `$rand` 연산자는 0에서 1 사이의 난수를 생성하는 데 사용됩니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="rand-examples"></a>

다음 예제에서는 `$rand` 연산자를 사용하여 `temp` 컬렉션에서 두 문서를 무작위로 선택하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.items.insertMany([
  { "name": "pencil", "quantity": 110 },
  { "name": "pen", "quantity": 159 }
])
```

**쿼리 예제**

```
db.items.aggregate([
  {
    $project: {
      randomValue: { $rand: {} }
    }
  }
])
```

**출력**

```
[
  {
    _id: ObjectId('6924a5edd66dcae121d29517'),
    randomValue: 0.8615243955294392
  },
  {
    _id: ObjectId('6924a5edd66dcae121d29518'),
    randomValue: 0.22815483022099903
  }
]
```

## 코드 예제
<a name="rand-code"></a>

`$rand` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('items');

  const result = await collection.aggregate([
    {
      $project: {
        randomValue: { $rand: {} }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
  db = client['test']
  collection = db['items']

  result = list(collection.aggregate([
      {
        "$project": {
          "randomValue": { "$rand": {} }
        }
      }
  ]))

  print(result)

  client.close()

example()
```

------

# \$1range
<a name="range"></a>

Amazon DocumentDB의 `$range` 집계 연산자는 지정된 범위 내에서 연속된 숫자 배열을 생성하는 데 사용됩니다. 이 연산자는 아래 예제와 같이 레이스에서 보조 스테이션의 마일 마커와 같은 숫자 시퀀스를 생성하는 데 특히 유용합니다.

**파라미터**
+ `start`: 범위의 시작 값입니다.
+ `end`: 범위의 종료 값입니다.
+ `step`: (선택 사항) 범위를 생성할 때 사용할 단계 값입니다. 제공되지 않은 경우 기본 단계 값은 1입니다.

## 예제(MongoDB 쉘)
<a name="range-examples"></a>

이 예제에서는 `$range` 운영자를 사용하여 자전거 레이스의 수도국에 대한 마일 마커를 생성합니다.

**샘플 문서 생성**

```
db.races.insertMany([
  { _id: 0, race: "STP", distance: 206 },
  { _id: 1, race: "RSVP", distance: 160 },
  { _id: 2, race: "Chilly Hilly", distance: 33 },
  { _id: 3, race: "Flying Wheels", distance: 100 }
]);
```

**쿼리 예제**

```
db.races.aggregate([
  {
    $project: {
      race: 1,
      "waterStations": { $range: [20, "$distance", 20] }
    }
  }
]);
```

**출력**

```
[
  {
    _id: 0,
    race: 'STP',
    waterStations: [
       20,  40,  60,  80,
      100, 120, 140, 160,
      180, 200
    ]
  },
  {
    _id: 1,
    race: 'RSVP',
    waterStations: [
       20,  40,  60, 80,
      100, 120, 140
    ]
  },
  { _id: 2, race: 'Chilly Hilly', waterStations: [ 20 ] },
  { _id: 3, race: 'Flying Wheels', waterStations: [ 20, 40, 60, 80 ] }
]
```

## 코드 예제
<a name="range-code"></a>

`$range` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();
    const db = client.db('test');
    const collection = db.collection('races');

    const pipeline = [
      {
        $project: {
          race: 1,
          waterStations: { $range: [20, "$distance", 20] } 
        }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();

    console.dir(results, { depth: null });

  } finally {
    await client.close();
  }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():

  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

  try:
      db = client.test
      collection = db.races

      pipeline = [
          {
              "$project": {
                  "race": 1,
                  "waterStations": { "$range": [20, "$distance", 20] }
              }
          }
      ]

      results = collection.aggregate(pipeline)

      for doc in results:
          print(doc)

  except Exception as e:
      print(f"An error occurred: {e}")

  finally:
      client.close()

example()
```

------

# \$1redact
<a name="redact"></a>

Amazon DocumentDB의 `$redact` 집계 단계는 지정된 필드의 값을 기반으로 출력 문서에서 콘텐츠를 선택적으로 포함하거나 제외하는 데 사용됩니다. 이는 액세스 수준 또는 사용자 권한에 따라 민감한 데이터의 가시성을 제어해야 하는 시나리오에서 특히 유용합니다.

**파라미터**
+ `$cond`: 문서의 각 필드에 `$$DESCEND` 대해 `$$PRUNE`, 또는 `$$KEEP`로 평가되는 표현식입니다.
+ `$$KEEP`: 출력 문서에 현재 필드를 유지합니다.
+ `$$PRUNE`: 출력 문서에서 현재 필드를 제거합니다.
+ `$$DESCEND`: 객체 또는 배열인 현재 필드에 `$redact` 스테이지를 반복적으로 적용합니다.

## 예제(MongoDB 쉘)
<a name="redact-examples"></a>

이 예제에서는 `$redact` 스테이지를 사용하여 상태를 기준으로 주문을 필터링하고 특정 상태 값이 있는 주문만 표시합니다.

**샘플 문서 생성**

```
db.orders.insert([
  { "_id": 1, "status": "shipped", "customer": "Carlos Salazar", "total": 150.00, "date": "2025-01-15" },
  { "_id": 2, "status": "processing", "customer": "Saanvi Sarkar", "total": 89.99, "date": "2025-01-20" },
  { "_id": 3, "status": "cancelled", "customer": "Zhang Wei", "total": 220.50, "date": "2025-01-18" }
])
```

**쿼리 예제**

```
db.orders.aggregate([
  {
    $redact: {
      $cond: {
        if: { $in: ["$status", ["shipped", "processing"]] },
        then: "$$KEEP",
        else: "$$PRUNE"
      }
    }
  }
])
```

**출력**

```
[
  { _id: 1, status: 'shipped', customer: 'Carlos Salazar', total: 150, date: '2025-01-15' },
  { _id: 2, status: 'processing', customer: 'Saanvi Sarkar', total: 89.99, date: '2025-01-20' }
]
```

이 예제에서 `$redact` 단계는 각 문서의 `status` 필드 값을 확인합니다. 이 "배송" 또는 "처리"`status`인 경우 문서는 보관됩니다(`$$KEEP`). 그렇지 않으면 문서가 정리됩니다(`$$PRUNE`).

## 코드 예제
<a name="redact-code"></a>

`$redact` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $redact: {
        $cond: {
          if: { $in: ['$status', ['shipped', 'processing']] },
          then: '$$KEEP',
          else: '$$PRUNE'
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.aggregate([
        {
            '$redact': {
                '$cond': {
                    'if': { '$in': ['$status', ['shipped', 'processing']] },
                    'then': '$$KEEP',
                    'else': '$$PRUNE'
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1reduce
<a name="reduce"></a>

Amazon DocumentDB의 `$reduce` 집계 연산자는 배열의 요소에 두 인수의 함수를 누적하여 적용하여 배열을 단일 값으로 줄이는 데 사용됩니다. 이 연산자는 집계 파이프라인 내의 배열 데이터에 대해 복잡한 계산 또는 변환을 수행하는 데 특히 유용합니다.

**파라미터**
+ `input`: 축소할 배열입니다.
+ `initialValue`: 축소 작업에 사용할 초기 값입니다.
+ `in`: `input` 배열의 각 요소에 대해 평가할 표현식입니다. 이 표현식은 축소의 다음 반복에 사용할 값을 반환해야 합니다.

## 예제(MongoDB 쉘)
<a name="reduce-examples"></a>

다음 예제에서는 `$reduce` 연산자를 사용하여 배열의 모든 요소 합계를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.orders.insertMany([
  { "_id": 1, "items": [1, 2, 3, 4, 5] },
  { "_id": 2, "items": [10, 20, 30] },
  { "_id": 3, "items": [5, 15, 25, 35] },
  { "_id": 4, "items": [100, 200] }
])
```

**쿼리 예제**

```
db.orders.aggregate([
  {
    $project: {
      total: {
        $reduce: {
          input: "$items",
          initialValue: 0,
          in: { $add: ["$$value", "$$this"] }
        }
      }
    }
  }
])
```

**출력**

```
[
  { "_id": 1, "total": 15 },
  { "_id": 2, "total": 60 },
  { "_id": 3, "total": 80 },
  { "_id": 4, "total": 300 }
]
```

`$reduce` 연산자는 `items` 배열을 반복하여 각 요소를 0`initialValue`의에 추가합니다. 결과는 배열에 있는 모든 요소의 합계입니다.

## 코드 예제
<a name="reduce-code"></a>

`$reduce` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

다음은 Node.js 애플리케이션에서 `$reduce` 연산자를 사용하는 예입니다.

```
const { MongoClient } = require("mongodb");

async function main() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const orders = db.collection("orders");

  const result = await orders.aggregate([
    {
      $project: {
        total: {
          $reduce: {
            input: "$items",
            initialValue: 0,
            in: { $add: ["$$value", "$$this"] }
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

다음은 Python 애플리케이션에서 `$reduce` 연산자를 사용하는 예입니다.

```
from pymongo import MongoClient

def main():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    orders = db["orders"]

    result = list(orders.aggregate([
        {
            "$project": {
                "total": {
                    "$reduce": {
                        "input": "$items",
                        "initialValue": 0,
                        "in": { "$add": ["$$value", "$$this"] }
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1regexFind
<a name="regexFind"></a>

버전 5.0에서 새로 추가되었습니다.

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$regexFind` 연산자는 문서 내의 문자열 필드에서 정규식 일치를 수행하는 데 사용됩니다. 이를 통해 지정된 정규식 패턴과 일치하는 특정 하위 문자열을 검색하고 추출할 수 있습니다.

**파라미터**
+ `input`: 검색할 문자열 필드 또는 표현식입니다.
+ `regex`: 일치시킬 정규식 패턴입니다.
+ `options`: (선택 사항) 대소문자 구분 및 여러 줄 일치와 같은 정규 표현식의 선택적 파라미터를 지정하는 객체입니다. 지원되는 옵션은 `i` (대/소문자 비구분) 및 `m` (다중 줄)입니다.

## 예제(MongoDB 쉘)
<a name="regexFind-examples"></a>

다음 예제에서는 `$regexFind` 연산자를 사용하여 `name` 필드가 특정 정규식 패턴과 일치하는 문서를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { "_id": 1, name: "John Doe", email: "john@example.com" },
  { "_id": 2, name: "Diego Ramirez", email: "diego@example.com" },
  { "_id": 3, name: "Alejandro Rosalez", email: "alejandro@example.com" },
  { "_id": 4, name: "Shirley Rodriguez", email: "shirley@example.com" }
]);
```

**쿼리 예제**

```
db.users.aggregate([
  {
    $project: {
      names: {
        $regexFind: { input: '$name', regex: 'j', options: 'i' }
      }
    }
  },
  { $match: {names: {$ne: null}}}
])
```

이 쿼리는 `name` 필드에 문자 "j"(대소문자 비구분)가 포함된 모든 문서를 반환합니다.

**출력**

```
[
  { _id: 1, names: { match: 'J', idx: 0, captures: [] } }
]
```

**참고:** 쿼리가 Amazon DocumentDB 플래너 버전 1을 사용하는 경우 힌트를 사용하여 인덱스를 활용해야 합니다. 힌트가 없으면 쿼리가 컬렉션 스캔을 수행할 수 있습니다. 플래너 버전을 확인하고 힌트 사용에 대해 자세히 알아보려면 [Amazon DocumentDB Query Planner 설명서](https://docs.aws.amazon.com/documentdb/latest/developerguide/query-planner.html)를 참조하세요.

## 코드 예제
<a name="regexFind-code"></a>

`$regexFind` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const results = await users.aggregate([
    { $project: { names: { $regexFind: { input: "$name", regex: "john", options: "i" }}}},
    { $match: {names: {$ne: null}}}
  ]).toArray();
  

  console.log(results);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']

results = list(users.aggregate([
    { "$project": { "names": { "$regexFind": { "input": "$name", "regex": "john", "options": "i" }}}},
    { "$match": {"names": {"$ne": None}}}
]))

print(results)

client.close()
```

------

# \$1regexFindAll
<a name="regexFindAll"></a>

5.0에 도입

Amazon DocumentDB의 `$regexFindAll` 연산자는 문서 내의 문자열 필드에서 정규식 일치를 수행하는 데 사용됩니다. 이를 통해 지정된 정규식 패턴과 일치하는 특정 하위 문자열을 검색하고 추출하여 정규식의 모든 일치 항목을 반환할 수 있습니다.

**파라미터**
+ `input`: 검색할 문자열 필드 또는 표현식입니다.
+ `regex`: 일치시킬 정규식 패턴입니다.
+ `options`: (선택 사항) 대소문자 구분 및 여러 줄 일치와 같은 정규 표현식의 선택적 파라미터를 지정하는 객체입니다. 지원되는 옵션은 `i` (대/소문자 비구분) 및 `m` (다중 줄)입니다.

## 예제(MongoDB 쉘)
<a name="regexFindAll-examples"></a>

다음 예제에서는 `$regexFindAll` 연산자를 사용하여 `email` 필드에서 모든 문자 시퀀스를 추출하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { _id: 1, name: "John Doe", email: "john@example.com", phone: "555-1234" },
  { _id: 2, name: "Jane Roe", email: "jane@example.com", phone: "555-5678" },
  { _id: 3, name: "Carlos Salazar", email: "carlos@example.com", phone: "555-3456" },
  { _id: 4, name: "Saanvi Sarkar", email: "saanvi@example.com", phone: "555-7890" }
  
]);
```

**쿼리 예제**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      emailMatches: {
        $regexFindAll: { input: '$email', regex: '[a-z]+', options: 'i' }
      }
    }
  }
])
```

**출력**

```
[
  {
    _id: 1,
    name: 'John Doe',
    emailMatches: [
      { match: 'john', idx: 0, captures: [] },
      { match: 'example', idx: 5, captures: [] },
      { match: 'com', idx: 13, captures: [] }
    ]
  },
  {
    _id: 2,
    name: 'Jane Roe',
    emailMatches: [
      { match: 'jane', idx: 0, captures: [] },
      { match: 'example', idx: 5, captures: [] },
      { match: 'com', idx: 13, captures: [] }
    ]
  },
  {
    _id: 3,
    name: 'Carlos Salazar',
    emailMatches: [
      { match: 'carlos', idx: 0, captures: [] },
      { match: 'example', idx: 7, captures: [] },
      { match: 'com', idx: 15, captures: [] }
    ]
  },
  {
    _id: 4,
    name: 'Saanvi Sarkar',
    emailMatches: [
      { match: 'saanvi', idx: 0, captures: [] },
      { match: 'example', idx: 7, captures: [] },
      { match: 'com', idx: 15, captures: [] }
    ]
  }
]
```

**참고:** 쿼리가 Amazon DocumentDB 플래너 버전 1을 사용하는 경우 힌트를 사용하여 인덱스를 활용해야 합니다. 힌트가 없으면 쿼리가 컬렉션 스캔을 수행할 수 있습니다. 플래너 버전을 확인하고 힌트 사용에 대해 자세히 알아보려면 [Amazon DocumentDB 쿼리 플래너 설명서](https://docs.aws.amazon.com/documentdb/latest/developerguide/query-planner.html)를 참조하세요.

## 코드 예제
<a name="regexFindAll-code"></a>

`$regexFindAll` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

다음은 Node.js 애플리케이션에서 `$regexFind` 연산자를 사용하는 예입니다.

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const results = await users.aggregate([
    {
      $project: {
        name: 1,
        emailMatches: {
          $regexFindAll: { input: "$email", regex: "[a-z]+", options: "i" }
        }
      }
    }
  ]).toArray();
  
  console.log(JSON.stringify(results, null, 2));

  await client.close();
}

main();
```

------
#### [ Python ]

다음은 Python 애플리케이션에서 `$regexFind` 연산자를 사용하는 예입니다.

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']

results = list(users.aggregate([
    { 
        "$project": { 
            "name": 1,
            "emailMatches": { 
                "$regexFindAll": { 
                    "input": "$email", 
                    "regex": "[a-z]+", 
                    "options": "i" 
                }
            }
        }
    }
]))

print(results)

client.close()
```

------

# \$1regexMatch
<a name="regexMatch"></a>

버전 5.0의 새 버전입니다. Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$regexMatch` 연산자는 문자열 필드에서 정규식 일치를 수행하는 데 사용됩니다. 입력 문자열이 지정된 패턴과 일치하는지 여부를 나타내는 부울 값(`true` 또는 `false`)을 반환합니다.

**파라미터**
+ `input`: 정규식에 대해 테스트할 문자열입니다.
+ `regex`: 일치시킬 정규식 패턴입니다.
+ `options`: (선택 사항) 대소문자를 구분하지 않는 일치() 또는 여러 줄 일치(`i`)와 같은 정규 표현식 동작을 수정하는 플래그입니다`m`.

## 예제(MongoDB 쉘)
<a name="regexMatch-examples"></a>

다음 예제에서는 `$regexMatch` 연산자를 사용하여 이름이 'M' 문자로 시작하는지 확인하는 방법을 보여줍니다. 연산자는 각 문서에 `false` 대해 `true` 또는를 반환합니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { "_id":1, name: "María García", email: "maría@example.com" },
  { "_id":2, name: "Arnav Desai", email: "arnav@example.com" },
  { "_id":3, name: "Martha Rivera", email: "martha@example.com" },
  { "_id":4, name: "Richard Roe", email: "richard@example.com" },

]);
```

**쿼리 예제**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      startsWithM: {
        $regexMatch: {
          input: "$name",
          regex: "^M",
          options: "i"
        }
      }
    }
  }
]);
```

**출력**

```
{ _id: 1, name: 'María García', startsWithM: true },
{ _id: 2, name: 'Arnav Desai', startsWithM: false },
{ _id: 3, name: 'Martha Rivera', startsWithM: true },
{ _id: 4, name: 'Richard Roe', startsWithM: false }
```

## 코드 예제
<a name="regexMatch-code"></a>

`$regexMatch` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function checkNamePattern() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.aggregate([
    {
      $project: {
        name: 1,
        startsWithM: {
          $regexMatch: {
            input: "$name",
            regex: "^M",
            options: "i"
          }
        }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

checkNamePattern();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def check_name_pattern():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.users

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'startsWithM': {
                    '$regexMatch': {
                        'input': '$name',
                        'regex': '^M',
                        'options': 'i'
                    }
                }
            }
        }
    ]))

    print(result)

    client.close()

check_name_pattern()
```

------

# \$1replaceAll
<a name="replaceAll"></a>

5.0에 도입

Amazon DocumentDB의 `$replaceAll` 연산자는 필드 내에서 지정된 문자열 패턴의 모든 발생을 새 문자열로 대체하는 데 사용됩니다. 이 연산자는 데이터 정규화, 텍스트 정리 및 문자열 조작과 같은 작업에 유용할 수 있습니다.

**파라미터**
+ `input`: 대체할 문자열이 포함된 필드 또는 표현식입니다.
+ `find`: 검색 및 대체할 문자열 패턴입니다.
+ `replacement`: 일치하는 발생을 대체할 문자열입니다.

## 예제(MongoDB 쉘)
<a name="replaceAll-examples"></a>

다음 예제에서는 집계 파이프라인에서 `$replaceAll` 연산자를 사용하여 문자열 "Chocolatier"의 모든 발생을 "Chocolate Co."로 대체하는 방법을 보여줍니다. "products" 컬렉션의 "brandName" 필드에

**샘플 문서 생성**

```
db.products.insertMany([
  {
    "_id": 1,
    "productId": "PROD-0Y9GL0",
    "brandName": "Gordon's Chocolatier",
    "category": "CPG",
    "rating": {
      "average": 4.8
    }
  },
  {
    "_id": 2,
    "productId": "PROD-1X2YZ3",
    "brandName": "Premium Chocolatier",
    "category": "CPG",
    "rating": {
      "average": 4.5
    }
  },
  {
    "_id": 3,
    "productId": "PROD-Y2E9H5",
    "name": "Nutrition Co. - Original Corn Flakes Cereal",
    "category": "Breakfast Cereals",
    "price": 8.5
  }
]);
```

**쿼리 예제**

```
db.products.aggregate([
  {
    $addFields: {
      "brandName": {
        $replaceAll: {
          input: "$brandName",
          find: "Chocolatier",
          replacement: "Chocolate Co."
        }
      }
    }
  }
])
```

**출력**

```
[
  {
    _id: 1,
    productId: 'PROD-0Y9GL0',
    brandName: "Gordon's Chocolate Co.",
    category: 'CPG',
    rating: { average: 4.8 }
  },
  {
    _id: 2,
    productId: 'PROD-1X2YZ3',
    brandName: 'Premium Chocolate Co.',
    category: 'CPG',
    rating: { average: 4.5 }
  },
  {
    _id: 3,
    productId: 'PROD-Y2E9H5',
    name: 'Nutrition Co. - Original Corn Flakes Cereal',
    category: 'Breakfast Cereals',
    price: 8.5,
    brandName: null
  }
]
```

## 코드 예제
<a name="replaceAll-code"></a>

`$replaceAll` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function replaceAll() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const results = await collection.aggregate([
    {
      $addFields: {
        "brandName": {
          $replaceAll: {
            input: "$brandName",
            find: "Chocolatier",
            replacement: "Chocolate Co."
          }
        }
      }
    }
  ]).toArray();

  console.log(results);

  await client.close();
}

replaceAll();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def replace_all():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    results = list(collection.aggregate([
        {
            "$addFields": {
                "brandName": {
                    "$replaceAll": {
                        "input": "$brandName",
                        "find": "Chocolatier",
                        "replacement": "Chocolate Co."
                    }
                }
            }
        }
    ]))

    print(results)

    client.close()

replace_all()
```

------

# \$1replaceOne
<a name="replaceOne"></a>

5.0에 도입

Amazon DocumentDB의 `$replaceOne` 연산자는 집계 파이프라인 내에서 문자열 내에서 지정된 하위 문자열의 첫 번째 발생을 대체 문자열로 대체하는 데 사용되는 문자열 표현식 연산자입니다. 이 연산자는 대/소문자를 구분하며 발견된 첫 번째 일치 항목만 대체합니다.

**파라미터**
+ `input`: 찾기를 수행할 문자열(필드)입니다.
+ `find`: 입력 내에서 검색할 문자열입니다.
+ `replacement`: 입력(필드)에서 찾기의 첫 번째 발생을 대체하는 문자열입니다.

## 예제(MongoDB 쉘)
<a name="replaceOne-examples"></a>

다음 예제에서는 집계 파이프라인 내에서 `$replaceOne` 연산자를 사용하여 제품 이름의 하위 문자열을 대체하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertMany([
  { "_id":1, "productId": "PROD-0Y9GL0", "name": "Gordon's Extra Creamy Milk Chocolate - Pack of 4", "category": "Confectionery", "price": 24.99 },
  { "_id":2, "productId": "PROD-Y2E9H5", "name": "Nutrition Co. - Original Corn Flakes Cereal", "category": "Breakfast Cereals", "price": 8.50 },
  { "_id":3, "productId": "PROD-Z3F8K2", "name": "Gordon's Dark Chocolate (90% Cocoa) Pack - Pack of 4", "category": "Confectionery", "price": 28.99 }
]);
```

**집계 예제**

```
db.products.aggregate([
  {
    $addFields: {
      standardizedName: {
        $replaceOne: {
          input: "$name",
          find: "Pack",
          replacement: "Package"
        }
      }
    }
  }
]);
```

**출력**

출력은 각 제품 이름에서 첫 번째로 발생한 "Pack"만 "Package"로 대체되었음을 보여줍니다.

```
[
  {
    _id: 1,
    productId: 'PROD-0Y9GL0',
    name: "Gordon's Extra Creamy Milk Chocolate - Pack of 4",
    category: 'Confectionery',
    price: 24.99,
    standardizedName: "Gordon's Extra Creamy Milk Chocolate - Package of 4"
  },
  {
    _id: 2,
    productId: 'PROD-Y2E9H5',
    name: 'Nutrition Co. - Original Corn Flakes Cereal',
    category: 'Breakfast Cereals',
    price: 8.5,
    standardizedName: 'Nutrition Co. - Original Corn Flakes Cereal'
  },
  {
    _id: 3,
    productId: 'PROD-Z3F8K2',
    name: "Gordon's Dark Chocolate (90% Cocoa) Pack - Pack of 4",
    category: 'Confectionery',
    price: 28.99,
    standardizedName: "Gordon's Dark Chocolate (90% Cocoa) Package - Pack of 4"
  }
```

## 코드 예제
<a name="replaceOne-code"></a>

`$replaceOne` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function replaceOne() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const pipeline = [
    {
      $addFields: {
        standardizedName: {
          $replaceOne: {
            input: '$name',
            find: 'Pack',
            replacement: 'Package'
          }
        }
      }
    }
  ];

  const result = await collection.aggregate(pipeline).toArray();
  console.log(result);

  await client.close();
}

replaceOne();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def replaceOne():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    pipeline = [
        {
            '$addFields': {
                'standardizedName': {
                    '$replaceOne': {
                        'input': '$name',
                        'find': 'Pack',
                        'replacement': 'Package'
                    }
                }
            }
        }
    ]

    result = list(collection.aggregate(pipeline))
    print(result)

    client.close()

replaceOne()
```

------

# \$1replaceRoot
<a name="replaceRoot"></a>

`$replaceRoot` 연산자는 루트 문서를 지정된 임베디드 문서로 대체하는 데 사용됩니다. 이는 중첩된 문서를 최상위 수준으로 승격하거나 데이터 출력을 재구성하려는 경우에 유용합니다.

**파라미터**
+ `newRoot`: 기존 루트 문서를 대체할 새 루트 문서입니다.

## 예제(MongoDB 쉘)
<a name="replaceRoot-examples"></a>

이 예제에서는 배송 레이블 또는 주소 목록을 생성하는 데 유용한 고객 주문에서 배송 주소 정보를 추출하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.orders.insertMany([
  {
    "_id":1, "orderId": "ORD-2024-001", "customerId": "CUST-12345", "orderDate": "2024-01-15", "shippingAddress": { "name": "María García", "street": "123 Main St", "city": "Seattle", "state": "WA", "zipCode": "98101", "country": "USA" },"totalAmount": 149.99 },
  { "_id":2, "orderId": "ORD-2024-002", "customerId": "CUST-67890", "orderDate": "2024-01-16", "shippingAddress": { "name": "Arnav Desai", "street": "456 Oak Ave", "city": "Portland", "state": "OR", "zipCode": "97201", "country": "USA" }, "totalAmount": 89.50 } ])
```

**쿼리 예제**

```
db.orders.aggregate([
  {
    $replaceRoot: {
      newRoot: "$shippingAddress"
    }
  }
])
```

**출력**

```
{
    name: 'María García',
    street: '123 Main St',
    city: 'Seattle',
    state: 'WA',
    zipCode: '98101',
    country: 'USA'
  },
  {
    name: 'Arnav Desai',
    street: '456 Oak Ave',
    city: 'Portland',
    state: 'OR',
    zipCode: '97201',
    country: 'USA'
  }
```

## 코드 예제
<a name="replaceRoot-code"></a>

`$replaceRoot` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function extractShippingAddresses() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $replaceRoot: {
        newRoot: "$shippingAddress"
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

extractShippingAddresses();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def extract_shipping_addresses():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.aggregate([
        {
            "$replaceRoot": {
                "newRoot": "$shippingAddress"
            }
        }
    ]))

    print(result)

    client.close()

extract_shipping_addresses()
```

------

# \$1replaceWith
<a name="replaceWith"></a>

버전 8.0의 새로운 기능

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$replaceWith` 집계 단계는 입력 문서를 새 문서로 대체하는 데 사용됩니다. \$1id 필드를 포함하여 입력 문서의 모든 기존 필드는 새 문서로 대체됩니다. `$replaceWith`는 일반적으로 문서를 평면화하거나 임베디드 문서를 최상위 수준으로 승격하는 데 사용됩니다.

**파라미터**
+ `<replacement>` (필수): 기존 문서를 대체할 새 문서입니다.

## 예제(MongoDB 쉘)
<a name="replaceWith-examples"></a>

다음 예제에서는 `$replaceWith` 연산자를 사용하여 Amazon DocumentDB 컬렉션의 기존 문서를 교체하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.restaurants.insertMany([
  {
    "restaurantId": "REST-0Y9GL0",
    "name": "Biryani Adda",
    "cuisine": "Indian",
    "ratings": [ 3, 4, 3, 2, 2, 4, 1, 5, 5, 5 ]
  },
  {
    "restaurantId": "REST-8L2PX9",
    "name": "The Burger Spot",
    "cuisine": "American",
    "ratings": [ 2, 3, 4, 5, 3, 1, 1, 2, 4 ]
  }
]);
```

**쿼리 예제**

```
db.restaurants.aggregate([
  { $replaceWith: {
      name: "$name",
      cuisine: "$cuisine",
      rating: { $avg: "$ratings" }
    }
  }
]);
```

**출력**

```
[
  {
    name: 'Biryani Adda',
    cuisine: 'Indian',
    rating: 3.4
  },
  {
    name: 'The Burger Spot',
    cuisine: 'American',
    rating: 2.7777777777777777
  }
]
```

## 코드 예제
<a name="replaceWith-code"></a>

`$replaceWith` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function replaceDoc() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('restaurants');

  const result = await collection.aggregate([
    { $replaceWith: {
        name: "description_index",
        cuisine: 2,
        rating: { $avg: "$ratings" }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

replaceDoc();
```

------
#### [ Python ]

```
from pymongo import MongoClient


def replace_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.restaurants

    result = list(collection.aggregate([
        {
            '$replaceWith': {
                'name': "$name",
                'cuisine': "$cuisine",
                'rating': { '$avg': "$ratings"}
            }
        }
    ]))

    print(result)
    client.close()

replace_document()
```

------

# \$1reverseArray
<a name="reverseArray"></a>

Amazon DocumentDB의 `$reverseArray` 연산자는 배열의 요소를 지정된 순서로 되돌리는 데 사용됩니다. 이 연산자는 배열의 요소를 역방향으로 재정렬해야 할 때 유용합니다.

**파라미터**
+ `expression`: 반전할 배열 표현식입니다.

## 예제(MongoDB 쉘)
<a name="reverseArray-examples"></a>

다음 예제에서는 `$reverseArray` 연산자를 사용하여 배열의 요소 순서를 반전하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.miles.insertMany([
  { "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ]},
  { "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 2560, 890, 2780]},
  { "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 880]}
]);
```

**쿼리 예제**

```
db.miles.aggregate([
  {
    $project: {
      _id: 1,
      member_since: 1,
      credit_card: 1,
      reversed_flight_miles: { $reverseArray: "$flight_miles" }
    }
  }
]);
```

**출력**

```
{ "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "reversed_flight_miles" : [ 880, 2560, 1205 ] }
{ "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "reversed_flight_miles" : [ 2780, 890, 2560, 1205 ] }
{ "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "reversed_flight_miles" : [ 880, 1205 ] }
```

이 예제에서는 `$reverseArray` 연산자를 사용하여 `flight_miles` 배열 순서를 반대로 지정합니다. 출력의 결과 `reversed_flight_miles` 필드에는 배열의 요소가 역순으로 표시됩니다.

## 코드 예제
<a name="reverseArray-code"></a>

`$reverseArray` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

다음은 Node.js 애플리케이션에서 `$reverseArray` 연산자를 사용하는 예입니다.

```
const { MongoClient } = require('mongodb');

async function reverseArray() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        member_since: 1,
        credit_card: 1,
        reversed_flight_miles: { $reverseArray: '$flight_miles' }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

reverseArray();
```

------
#### [ Python ]

다음은 Python 애플리케이션에서 `$reverseArray` 연산자를 사용하는 예입니다.

```
from pymongo import MongoClient

def reverse_array():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.miles

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'member_since': 1,
                'credit_card': 1,
                'reversed_flight_miles': { '$reverseArray': '$flight_miles' }
            }
        }
    ]))

    print(result)
    client.close()

reverse_array()
```

------

# \$1rtrim
<a name="rtrim"></a>

버전 4.0의 새 버전입니다.

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$rtrim` 연산자는 문자열에서 후행 문자를 제거하는 데 사용됩니다. 기본적으로 후행 공백 문자를 제거하지만 문자 인수를 전달하여 제거할 문자 집합을 지정할 수도 있습니다.

**파라미터**
+ `input`: 후행 공백 문자를 제거할 입력 문자열입니다.
+ `chars`: (선택 사항) 특정 문자를 제거합니다.

## 예제(MongoDB 쉘)
<a name="rtrim-examples"></a>

다음 예제에서는 `$rtrim` 연산자를 사용하여 문자열에서 후행 지정 문자(" \$1")를 제거하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insert([
  { "name": "John Doe*  ", "age": 30 },
  { "name": "Jane Smith  ", "age": 25 },
  { "name": "Bob Johnson", "age": 35 }
]);
```

**쿼리 예제**

```
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      name: { $rtrim: { input: "$name", chars: " *" } }, 
      age: 1
    }
  }
]);
```

**출력**

```
[
  { age: 30, name: 'John Doe' },
  { age: 25, name: 'Jane Smith' },
  { age: 35, name: 'Bob Johnson' }
]
```

## 코드 예제
<a name="rtrim-code"></a>

`$rtrim` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient, Bson } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {

    const db = client.db('test');
    const collection = db.collection('collection');  

    const pipeline = [
      {
        $project: {
          _id: 0,
          name: { $rtrim: { input: "$name", chars: " *" } },
          age: 1
        }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();
    console.dir(results, { depth: null });

  } catch (err) {
    console.error('Error occurred:', err);
  } finally {
    await client.close();
  }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    try:

        db = client.test
        collection = db.collection

        pipeline = [
            {
                "$project": {
                    "_id": 0,
                    "name": { "$rtrim": { "input": "$name", "chars": " *" } },
                    "age": 1
                }
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        client.close()

example()
```

------

# \$1sample
<a name="sample"></a>

Amazon DocumentDB의 `$sample` 집계 단계는 컬렉션에서 지정된 수의 문서를 무작위로 선택하는 데 사용됩니다. 이는 데이터 분석, 테스트 및 추가 처리를 위한 샘플 생성과 같은 작업에 유용합니다.

**파라미터**
+ `size`: 임의로 선택할 문서 수입니다.

## 예제(MongoDB 쉘)
<a name="sample-examples"></a>

다음 예제에서는 `$sample` 스테이지를 사용하여 `temp` 컬렉션에서 두 문서를 무작위로 선택하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.temp.insertMany([
  { "_id": 1, "temperature": 97.1, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 2, "temperature": 98.2, "humidity": 0.59, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 3, "temperature": 96.8, "humidity": 0.61, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 4, "temperature": 97.9, "humidity": 0.61, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 5, "temperature": 97.5, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 6, "temperature": 98.0, "humidity": 0.59, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 7, "temperature": 97.2, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 8, "temperature": 98.1, "humidity": 0.59, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 9, "temperature": 96.9, "humidity": 0.62, "timestamp": ISODate("2019-03-21T21:17:22.425Z") },
  { "_id": 10, "temperature": 97.7, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }
]);
```

**쿼리 예제**

```
db.temp.aggregate([
   { $sample: { size: 2 } }
])
```

**출력**

```
{ "_id" : 4, "temperature" : 97.9, "humidity" : 0.61, "timestamp" : ISODate("2019-03-21T21:17:22.425Z") }
{ "_id" : 9, "temperature" : 96.9, "humidity" : 0.62, "timestamp" : ISODate("2019-03-21T21:17:22.425Z") }
```

결과에 따르면 문서 10개 중 2개가 무작위로 샘플링되었습니다. 이제 이러한 문서를 사용하여 평균을 결정하거나 최소/최대 계산을 수행할 수 있습니다.

## 코드 예제
<a name="sample-code"></a>

`$sample` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function sampleDocuments() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('temp');

  const result = await collection.aggregate([
    { $sample: { size: 2 } }
  ]).toArray();

  console.log(result);
  await client.close();
}

sampleDocuments();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def sample_documents():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['temp']

    result = list(collection.aggregate([
        { '$sample': { 'size': 2 } }
    ]))

    print(result)
    client.close()

sample_documents()
```

------

# \$1search
<a name="search"></a>

버전 5.0에서 새로 추가되었습니다.

Amazon DocumentDB의 `$search` 연산자는 텍스트 검색 기능을 제공하는 데 사용됩니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="search-examples"></a>

다음 예제에서는 `$search` 연산자를 사용하여 텍스트 검색 쿼리를 수행하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.textcollection.createIndex({"description": "text"});

db.textcollection.insertMany([
  { _id: 1, name: "John Doe", description: "This is a sample document about John Doe." },
  { _id: 2, name: "Jane Smith", description: "This is a sample document about Jane Smith." },
  { _id: 3, name: "Bob Johnson", description: "This is a sample document about Bob Johnson." },
  { _id: 4, name: "Jon Jeffries", description: "This is a sample document about Jon Jeffries." }
]);
```

**쿼리 예제**

```
db.textcollection.find(
  { $text: { $search: "John" } }
);
```

**출력**

```
[
  {
    _id: 1,
    name: 'John Doe',
    description: 'This is a sample document about John Doe.'
  }
]
```

## 코드 예제
<a name="search-code"></a>

`$search` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findWithText() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('textcollection');

  const result = await collection.find(
    { $text: { $search: "John" } }
  ).sort({ score: { $meta: "textScore" } }).toArray();

  console.log(result);
  client.close();
}

findWithText();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_with_text():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['textcollection']

    result = list(collection.find(
        { '$text': { '$search': 'John' } }
    ))

    print(result)
    client.close()

find_with_text()
```

------

# \$1second
<a name="second"></a>

Amazon DocumentDB의 `$second` 연산자는 날짜 또는 타임스탬프에서 초 단위 구성 요소를 추출합니다. 날짜 또는 타임스탬프 필드에서 초 값을 검색하는 데 사용됩니다.

**파라미터**
+ `expression`: 초 값을 추출할 날짜 또는 타임스탬프 필드입니다. 이 표현식은 필드 경로이거나 날짜 또는 타임스탬프로 확인되는 유효한 표현식일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="second-examples"></a>

다음 예제에서는 `$second` 연산자를 사용하여 날짜 필드에서 초 구성 요소를 추출하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { name: "John", dob: new Date("1990-05-15T12:30:45Z") },
  { name: "Jane", dob: new Date("1985-09-20T23:59:59Z") },
  { name: "Bob", dob: new Date("2000-01-01T00:00:00Z") }
]);
```

**쿼리 예제**

```
db.users.aggregate([{ $project: { name: 1, dobSeconds: { $second: "$dob" } } }])
```

**출력**

```
[
  { "_id" : ObjectId("6089a9c306a829d1f8b456a1"), "name" : "John", "dobSeconds" : 45 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a2"), "name" : "Jane", "dobSeconds" : 59 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a3"), "name" : "Bob", "dobSeconds" : 0 }
]
```

## 코드 예제
<a name="second-code"></a>

`$second` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([{ $project: { name: 1, dobSeconds: { $second: '$dob' } } }]).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = list(users.aggregate([{'$project': {'name': 1, 'dobSeconds': {'$second': '$dob'}}}]))
    print(result)

    client.close()

example ()
```

------

# \$1set
<a name="set-stage"></a>

버전 8.0의 새로운 기능

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$set` 집계 단계를 사용하면 집계 파이프라인 중에 설명서의 새 필드를 추가하거나 기존 필드 값을 업데이트할 수 있습니다.

**파라미터**
+ `expression`: 평가할 표현식입니다. 필드 참조 및 산술 연산을 포함하여 유효한 집계 표현식일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="set-stage-examples"></a>

다음 예제에서는 `$set` 집계 단계를 사용하여 `quantity` 필드에 `price` 필드를 곱하여 합계를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**집계 예제**

```
db.inventory.aggregate([
  {
    $set: {
      total: { $multiply: ["$quantity", "$price"] }
    }
  }
])
```

**출력**

```
[
  {
    _id: ObjectId('69248951d66dcae121d2950d'),
    item: 'pencil',
    quantity: 100,
    price: 0.24,
    total: 24
  },
  {
    _id: ObjectId('69248951d66dcae121d2950e'),
    item: 'pen',
    quantity: 204,
    price: 1.78,
    total: 363.12
  }
]
```

## 코드 예제
<a name="set-stage-code"></a>

`$set` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const inventory = db.collection('inventory');

  const result = await inventory.aggregate([
      {
        $set: {
          total: { $multiply: ["$quantity", "$price"] }
        }
      }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    inventory = db['inventory']

    result = list(inventory.aggregate([
      {
        "$set": {
          "total": { "$multiply": ["$quantity", "$price"] }
        }
      }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1setDifference
<a name="setDifference"></a>

버전 4.0의 새 버전입니다.

Amazon DocumentDB의 `$setDifference` 연산자는 두 세트를 비교하고 첫 번째 세트에는 있지만 두 번째 세트에는 없는 요소를 반환하는 데 사용됩니다. 이 연산자는 두 세트 사이의 고유한 요소를 찾는 데 유용합니다.

**파라미터**
+ `firstSet` : 비교할 첫 번째 세트입니다.
+ `secondSet` : 비교할 두 번째 세트입니다.

## 예제(MongoDB 쉘)
<a name="setDifference-examples"></a>

다음 예제에서는 `$setDifference` 연산자를 사용하여 두 세트 간의 고유한 요소를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry", "date"] },
  { _id: 2, fruits: ["banana", "cherry", "date", "elderberry"] }
]);
```

**쿼리 예제**

```
db.collection.aggregate([
  {
    $project: {
      uniqueFruits: { $setDifference: ["$fruits", ["banana", "cherry", "date"]] }
    }
  }
]);
```

**출력**

```
[
  { "_id": 1, "uniqueFruits": ["apple"] },
  { "_id": 2, "uniqueFruits": ["elderberry"] }
]
```

쿼리는 다음 단계를 수행합니다.

1. `$project` 스테이지를 사용하여 각 문서에 `uniqueFruits` 대한 새 필드를 생성합니다.

2. 연`$setDifference`산자는 `fruits` 배열을 배열과 비교`[&quot;banana&quot;, &quot;cherry&quot;, &quot;date&quot;]`하고 `fruits` 배열의 고유 요소를 반환합니다.

## 코드 예제
<a name="setDifference-code"></a>

`$setDifference` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

다음은 Node.js 애플리케이션에서 `$setDifference` 연산자를 사용하는 방법의 예입니다.

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('mycollection');

  // Insert sample documents
  await collection.insertMany([
    { _id: 1, fruits: ["apple", "banana", "cherry", "date"] },
    { _id: 2, fruits: ["banana", "cherry", "date", "elderberry"] }
  ]);

 // Query using $setDifference
  const result = await collection.aggregate([
    {
      $project: {
        uniqueFruits: { $setDifference: ["$fruits", ["banana", "cherry", "date"]] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

다음은 Python 애플리케이션에서 `$setDifference` 연산자를 사용하는 방법의 예입니다.

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['mycollection']

    # Insert sample documents
    collection.insert_many([
        {'_id': 1, 'fruits': ["apple", "banana", "cherry", "date"]},
        {'_id': 2, 'fruits': ["banana", "cherry", "date", "elderberry"]}
    ])

    # Query using $setDifference
    result = list(collection.aggregate([
        {
            '$project': {
                'uniqueFruits': {'$setDifference': ['$fruits', ["banana", "cherry", "date"]]}
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1setEquals
<a name="setEquals"></a>

Amazon DocumentDB의 `$setEquals` 연산자는 두 세트가 동일한지 확인하는 데 사용됩니다. 두 배열을 비교하고 순서에 관계없이 동일한 고유 요소를 포함하는 `true` 경우를 반환합니다.

**파라미터**
+ `expression1`: 비교할 첫 번째 배열입니다.
+ `expression2`: 비교할 두 번째 배열입니다.

## 예제(MongoDB 쉘)
<a name="setEquals-examples"></a>

다음 예제에서는 연`$setEquals`산자를 사용하여 두 값 세트를 비교하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry"] },
  { _id: 2, fruits: ["banana", "apple", "cherry"] },
  { _id: 3, fruits: ["apple", "banana", "orange"] }
])
```

**쿼리 예제**

```
db.collection.find({
  $expr: {
    $setEquals: ["$fruits", ["apple", "banana", "cherry"]]
  }
})
```

**출력**

```
{ "_id" : 1, "fruits" : [ "apple", "banana", "cherry" ] }
{ "_id" : 2, "fruits" : [ "banana", "apple", "cherry" ] }
```

쿼리는 `$setEquals` 연산자를 사용하여 각 문서의 `fruits` 필드를 배열과 비교합니다`[&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]`. `fruits` 필드가 비교 배열과 동일한 문서가 반환됩니다.

## 코드 예제
<a name="setEquals-code"></a>

`$setEquals` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('mycollection');

  // Insert sample documents
  await collection.insertMany([
    { _id: 1, fruits: ["apple", "banana", "cherry"] },
    { _id: 2, fruits: ["banana", "apple", "cherry"] },
    { _id: 3, fruits: ["apple", "banana", "orange"] }
  ]);

  // Query using $setEquals
  const result = await collection.find({
    $expr: {
      $setEquals: ["$fruits", ["apple", "banana", "cherry"]]
    }
  }).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['mycollection']

    # Insert sample documents
    collection.insert_many([
        {"_id": 1, "fruits": ["apple", "banana", "cherry"]},
        {"_id": 2, "fruits": ["banana", "apple", "cherry"]},
        {"_id": 3, "fruits": ["apple", "banana", "orange"]}
    ])

    # Query using $setEquals
    result = list(collection.find({
        "$expr": {
            "$setEquals": ["$fruits", ["apple", "banana", "cherry"]]
        }
    }))

    print(result)
    client.close()

example()
```

------

# \$1setIntersection
<a name="setIntersection"></a>

Amazon DocumentDB의 `$setIntersection` 연산자는 두 개 이상의 배열 간에 공통 요소를 반환하는 데 사용됩니다. 이 연산자는 데이터 세트로 작업할 때 특히 유용하므로 여러 세트의 교차점을 찾을 수 있습니다.

**파라미터**
+ `array1`: 교차할 첫 번째 배열입니다.
+ `array2`: 교차할 두 번째 배열입니다.
+ `arrayN`: (선택 사항) 교차할 추가 배열입니다.

## 예제(MongoDB 쉘)
<a name="setIntersection-examples"></a>

다음 예제에서는 `$setIntersection` 연산자를 사용하여 두 배열 간의 공통 요소를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { _id: 1, colors: ["red", "blue", "green"] },
  { _id: 2, colors: ["blue", "yellow", "orange"] },
  { _id: 3, colors: ["red", "green", "purple"] }
])
```

**쿼리 예제**

```
db.collection.aggregate([
  { $project: {
      _id: 1,
      commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
    }
  }
])
```

**출력**

```
[
  { "_id": 1, "commonColors": ["red", "blue", "green"] },
  { "_id": 2, "commonColors": ["blue"] },
  { "_id": 3, "commonColors": ["red", "green"] }
]
```

## 코드 예제
<a name="setIntersection-code"></a>

`$setIntersection` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('mycollection');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['mycollection']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'commonColors': { '$setIntersection': ["$colors", ["red", "blue", "green"]] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1setIsSubset
<a name="setIsSubset"></a>

Amazon DocumentDB의 `$setIsSubset` 연산자는 값 집합이 다른 집합의 하위 집합인지 확인하는 데 사용됩니다. 배열 필드에 대해 세트 기반 비교 및 작업을 수행하는 데 유용합니다.

**파라미터**
+ `field`: `$setIsSubset` 연산자를 적용할 필드입니다.
+ `set`: 필드를 비교할 집합입니다.

## 예제(MongoDB 쉘)
<a name="setIsSubset-examples"></a>

다음 예제에서는 연`$setIsSubset`산자를 사용하여 `tags` 필드가 지정된 세트의 하위 집합인지 확인하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertMany([
  { _id: 1, name: "Product A", tags: ["tag1", "tag2", "tag3"] },
  { _id: 2, name: "Product B", tags: ["tag1", "tag2"] },
  { _id: 3, name: "Product C", tags: ["tag2", "tag3"] }
]);
```

**쿼리 예제**

```
db.products.find({
  $expr: { $setIsSubset: [["tag1", "tag2"], "$tags"] }
})
```

\$1참고:\$1`$setIsSubset`는 집계 연산자이며 find() 쿼리에서 직접 사용할 수 없습니다. 이 예제에서는 `$expr`를와 함께 사용하여 쿼리 연산자와 집계 표현식 간의 차이를 `find()` 연결합니다.

**출력**

```
[
  { "_id" : 1, "name" : "Product A", "tags" : [ "tag1", "tag2", "tag3" ] },
  { "_id" : 2, "name" : "Product B", "tags" : [ "tag1", "tag2" ] }
]
```

쿼리는 `tags` 필드가 집합의 하위 집합인 문서를 반환합니다`[&quot;tag1&quot;, &quot;tag2&quot;]`.

## 코드 예제
<a name="setIsSubset-code"></a>

`$setIsSubset` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.find({
    $expr: { $setIsSubset: [["tag1", "tag2"], "$tags"] }
  }).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.find({
        '$expr': {'$setIsSubset': [['tag1', 'tag2'], '$tags']}
    }))

    print(result)

    client.close()

example()
```

------

# \$1setUnion
<a name="setUnion"></a>

Amazon DocumentDB의 `$setUnion` 집계 연산자는 두 개 이상의 값 세트를 결합하고 입력 세트의 모든 고유 요소가 포함된 세트를 반환하는 데 사용됩니다. 이 연산자는 문서의 배열 필드에 대해 설정 기반 작업을 수행해야 할 때 유용합니다.

**파라미터**
+ `expression1`: 배열로 확인되는 표현식입니다.
+ `expression2`: 배열로 확인되는 표현식입니다.
+ `expressionN`: 배열로 확인되는 추가 표현식(선택 사항).

## 예제(MongoDB 쉘)
<a name="setUnion-examples"></a>

다음 예제에서는 `$setUnion` 연산자를 사용하여 컬렉션에 있는 두 배열 필드의 고유 요소를 결합하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { _id: 1, name: "Alice", hobbies: ["reading", "swimming"], skills: ["coding", "writing"] },
  { _id: 2, name: "Bob", hobbies: ["cooking", "gardening"], skills: ["coding", "photography"] },
  { _id: 3, name: "Charlie", hobbies: ["reading", "painting"], skills: ["gardening", "music"] }
]);
```

**쿼리 예제**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      allInterests: { $setUnion: ["$hobbies", "$skills"] }
    }
  }
]);
```

**출력**

```
[
  { "_id" : 1, "name" : "Alice", "allInterests" : [ "coding", "reading", "swimming", "writing" ] },
  { "_id" : 2, "name" : "Bob", "allInterests" : [ "coding", "cooking", "gardening", "photography" ] },
  { "_id" : 3, "name" : "Charlie", "allInterests" : [ "gardening", "music", "painting", "reading" ] }
]
```

이 예제에서는 `$setUnion` 연산자를 사용하여 각 사용자 문서에 대한 `hobbies` 및 `skills` 배열 필드의 고유한 요소를 결합합니다. 결과 `allInterests` 필드에는 각 사용자의 모든 고유한 취미와 기술이 결합되어 있습니다.

## 코드 예제
<a name="setUnion-code"></a>

`$setUnion` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([
    {
      $project: {
        _id: 1,
        name: 1,
        allInterests: { $setUnion: ["$hobbies", "$skills"] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = list(users.aggregate([
        {
            '$project': {
                '_id': 1,
                'name': 1,
                'allInterests': { '$setUnion': ["$hobbies", "$skills"] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1skip
<a name="skip"></a>

Amazon DocumentDB에서는 `$skip` 연산자를 사용하여 쿼리 결과의 시작점을 오프셋하므로 일치하는 문서의 특정 하위 집합을 검색할 수 있습니다. 이는 결과의 후속 페이지를 검색하려는 페이지 매김 시나리오에서 특히 유용합니다.

**파라미터**
+ `skip`: 나머지 문서를 반환하기 전에 건너뛸 문서 수입니다.

## 예제(MongoDB 쉘)
<a name="skip-examples"></a>

다음 예제에서는 `$skip` 연산자를 사용하여 컬렉션에서 결과의 두 번째 페이지(문서 11\$120)를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insert([
  { "name": "Document 1" },
  { "name": "Document 2" },
  { "name": "Document 3" },
  { "name": "Document 4" },
  { "name": "Document 5" },
  { "name": "Document 6" },
  { "name": "Document 7" },
  { "name": "Document 8" },
  { "name": "Document 9" },
  { "name": "Document 10" },
  { "name": "Document 11" },
  { "name": "Document 12" },
  { "name": "Document 13" },
  { "name": "Document 14" },
  { "name": "Document 15" },
  { "name": "Document 16" },
  { "name": "Document 17" },
  { "name": "Document 18" },
  { "name": "Document 19" },
  { "name": "Document 20" }
]);
```

**쿼리 예제**

```
db.collection.find({}, { "name": 1 })
             .skip(10)
             .limit(10);
```

**출력**

```
[
  { "_id" : ObjectId("..."), "name" : "Document 11" },
  { "_id" : ObjectId("..."), "name" : "Document 12" },
  { "_id" : ObjectId("..."), "name" : "Document 13" },
  { "_id" : ObjectId("..."), "name" : "Document 14" },
  { "_id" : ObjectId("..."), "name" : "Document 15" },
  { "_id" : ObjectId("..."), "name" : "Document 16" },
  { "_id" : ObjectId("..."), "name" : "Document 17" },
  { "_id" : ObjectId("..."), "name" : "Document 18" },
  { "_id" : ObjectId("..."), "name" : "Document 19" },
  { "_id" : ObjectId("..."), "name" : "Document 20" }
]
```

## 코드 예제
<a name="skip-code"></a>

`$skip` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const results = await collection.find({}, { projection: { name: 1 } })
                                 .skip(10)
                                 .limit(10)
                                 .toArray();

  console.log(results);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.mydatabase
    collection = db.collection

    results = list(collection.find({}, {'name': 1})
                   .skip(10)
                   .limit(10))

    print(results)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1slice
<a name="slice"></a>

`$slice` 집계 연산자를 사용하면 배열의 시작 또는 끝에서 배열을 통과하여 배열의 하위 집합을 반환할 수 있습니다. 이는 상단 또는 하단 N 항목과 같이 배열 필드의 제한된 수의 항목을 표시하는 데 사용됩니다.

**파라미터**
+ `array`: 조각화할 배열 필드입니다.
+ `n`: 반환할 요소 수를 지정하는 정수입니다. 양수 값은 배열의 시작 부분부터 시작하고 음수 값은 배열의 끝 부분부터 시작합니다.

## 예제(MongoDB 쉘)
<a name="slice-examples"></a>

다음 예제에서는를 사용하여 각 셰프에 대해 처음 두 가지 좋아하는 달콤함을 반환`$slice`하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.sweets.insertMany([
  { "_id" : 1, "name" : "Alvin", "favorites": [ "chocolate", "cake", "toffee", "beignets" ] },
  { "_id" : 2, "name" : "Tom", "favorites": [ "donuts", "pudding", "pie" ] },
  { "_id" : 3, "name" : "Jessica", "favorites": [ "fudge", "smores", "pudding", "cupcakes" ] },
  { "_id" : 4, "name" : "Rachel", "favorites": [ "ice cream" ] }
]);
```

**쿼리 예제**

```
db.sweets.aggregate([
  { $project: { _id: 0, name: 1, topTwoFavorites: { $slice: [ "$favorites", 2 ] } } }
]);
```

**출력**

```
[
  { name: 'Alvin', topTwoFavorites: [ 'chocolate', 'cake' ] },
  { name: 'Tom', topTwoFavorites: [ 'donuts', 'pudding' ] },
  { name: 'Jessica', topTwoFavorites: [ 'fudge', 'smores' ] },
  { name: 'Rachel', topTwoFavorites: [ 'ice cream' ] }
]
```

이 예제에서는 `$slice` 연산자를 사용하여 각 문서의 `favorites` 배열에서 처음 두 요소를 추출합니다.

## 코드 예제
<a name="slice-code"></a>

`$slice` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('sweets');

  const result = await collection.aggregate([
    { $project: { name: 1, topTwoFavorites: { $slice: ['$favorites', 2] } } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['sweets']

    result = list(collection.aggregate([
        { '$project': { 'name': 1, 'topTwoFavorites': { '$slice': ['$favorites', 2] } } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1size
<a name="size"></a>

`$size` 연산자는 배열 필드 내의 항목 수를 반환하는 데 사용됩니다. 이는 문서에 저장된 배열의 요소 수를 결정하는 데 사용할 수 있습니다.

**파라미터**
+ `field`: 반환하려는 배열 크기의 필드 경로입니다.

## 예제(MongoDB 쉘)
<a name="size-examples"></a>

이 예제에서는 `$size` 연산자를 사용하여 각 사용자가 팔로우하는 팀 수를 반환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.profiles.insertMany([
  { _id: 1, name: "John Doe", teams: ["Acme", "Widgets", "Gadgets"] },
  { _id: 2, name: "Jane Smith", teams: ["Acme", "Gadgets"] },
  { _id: 3, name: "Bob Johnson", teams: ["Acme", "Widgets", "Gadgets"] }
]);
```

**쿼리 예제**

```
db.profiles.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      "numberOfTeams": { $size: "$teams" }
    }
  }
])
```

**출력**

```
[
  { name: 'John Doe', numberOfTeams: 3 },
  { name: 'Jane Smith', numberOfTeams: 2 },
  { name: 'Bob Johnson', numberOfTeams: 3 }
]
```

## 코드 예제
<a name="size-code"></a>

`$size` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const profiles = db.collection('profiles');

  const result = await profiles.aggregate([
    {
      $project: {
        item: 1,
        "numberOfTeams": { $size: "$teams" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    profiles = db.profiles

    result = list(profiles.aggregate([
        {
            '$project': {
                'item': 1,
                'numberOfTeams': { '$size': '$teams' }
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1sort
<a name="sort"></a>

`$sort` 집계 단계는 지정된 필드 값을 기반으로 파이프라인의 문서를 정렬합니다. 문서는 제공된 정렬 기준에 따라 오름차순 또는 내림차순으로 정렬됩니다.

**파라미터**
+ `field`: 정렬 기준으로 사용할 필드 이름입니다.
+ `order`: 오`1`름차순 또는 내림차순에 `-1` 사용합니다.

## 예제(MongoDB 쉘)
<a name="sort-examples"></a>

다음 예제에서는 `$sort` 스테이지를 사용하여 가격별로 제품을 내림차순으로 주문하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", category: "Electronics", price: 1200 },
  { _id: 2, name: "Mouse", category: "Electronics", price: 25 },
  { _id: 3, name: "Desk", category: "Furniture", price: 350 },
  { _id: 4, name: "Chair", category: "Furniture", price: 150 },
  { _id: 5, name: "Monitor", category: "Electronics", price: 400 }
]);
```

**쿼리 예제**

```
db.products.aggregate([
  { $sort: { price: -1 } }
]);
```

**출력**

```
[
  { _id: 1, name: 'Laptop', category: 'Electronics', price: 1200 },
  { _id: 5, name: 'Monitor', category: 'Electronics', price: 400 },
  { _id: 3, name: 'Desk', category: 'Furniture', price: 350 },
  { _id: 4, name: 'Chair', category: 'Furniture', price: 150 },
  { _id: 2, name: 'Mouse', category: 'Electronics', price: 25 }
]
```

## 코드 예제
<a name="sort-code"></a>

`$sort` 집계 단계 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.aggregate([
    { $sort: { price: -1 } }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.aggregate([
        { '$sort': { 'price': -1 } }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1split
<a name="split"></a>

Amazon DocumentDB의 `$split` 집계 연산자는 지정된 구분 기호를 기반으로 문자열을 하위 문자열 배열로 분할하는 데 사용됩니다. 이는 복잡한 문자열 필드를 구문 분석하고 추가 처리를 위해 개별 구성 요소를 추출하는 데 유용할 수 있습니다.

**파라미터**
+ `string`: 분할할 문자열입니다.
+ `delimiter`: 입력 문자열을 분할하는 데 사용되는 문자열입니다.

## 예제(MongoDB 쉘)
<a name="split-examples"></a>

이 예제에서는 `$split`를 사용하여 "데스크" 필드의 구성 요소를 배열로 분리하므로 데이터를 더 쉽게 처리할 수 있습니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
```

**쿼리 예제**

```
db.people.aggregate([
  { $project: { parts: { $split: ["$Desk", "-"] } } }
]);
```

**출력**

```
{ "_id" : 1, "parts" : [ "Düsseldorf", "BVV", "021" ] }
{ "_id" : 2, "parts" : [ "Munich", "HGG", "32a" ] }
{ "_id" : 3, "parts" : [ "Cologne", "ayu", "892.50" ] }
{ "_id" : 4, "parts" : [ "Dortmund", "Hop", "78" ] }
```

의 출력은 애플리케이션에서 직원의 정보를 표시하는 데 사용할 수 있는 배열을 `$split` 생성합니다.

## 코드 예제
<a name="split-code"></a>

`$split` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const result = await db.collection('people').aggregate([
    { $project: { parts: { $split: ['$Desk', '-'] } } }
  ]).toArray();
  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    result = list(db.people.aggregate([
        { '$project': { 'parts': { '$split': ['$Desk', '-'] } } }
    ]))
    print(result)
    client.close()

example()
```

------

# \$1sqrt
<a name="sqrt"></a>

버전 4.0에서 새로 추가되었습니다.

Amazon DocumentDB의 `$sqrt` 연산자는 숫자의 제곱근을 계산하는 데 사용됩니다.

**파라미터**
+ `expression`: 인수는 음수가 아닌 숫자로 확인되는 한 유효한 표현식일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="sqrt-examples"></a>

다음 예제에서는 `$sqrt` 연산자를 사용하여 숫자의 제곱근을 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.numbers.insertMany([
  { "_id": 1, "number": 16 },
  { "_id": 2, "number": 36 },
  { "_id": 3, "number": 64 }
]);
```

**쿼리 예제**

```
db.numbers.aggregate([
  { $project: {
    "_id": 1,
    "square_root": { $sqrt: "$number" }
  }}
]);
```

**출력**

```
[
  { _id: 1, square_root: 4 },
  { _id: 2, square_root: 6 },
  { _id: 3, square_root: 8 }
]
```

## 코드 예제
<a name="sqrt-code"></a>

`$sqrt` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
      await client.connect();

      const db = client.db('test');
      const collection = db.collection('numbers');

      const pipeline = [
        {
          $project: {
            _id: 1,
            square_root: { $sqrt: '$number' }
          }
        }
      ];

      const results = await collection.aggregate(pipeline).toArray();

      console.dir(results, { depth: null });

    } finally {
      await client.close();
    }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
  
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

  try:
      db = client.test
      collection = db.numbers

      pipeline = [
          {
              "$project": {
                  "_id": 1,
                  "square_root": { 
                    "$sqrt": "$number" 
                  }
              }
          }
      ]

      results = collection.aggregate(pipeline)

      for doc in results:
          print(doc)

  except Exception as e:
      print(f"An error occurred: {e}")

  finally:
      client.close()

example()
```

------

# \$1strLenBytes
<a name="strLenBytes"></a>

Amazon DocumentDB의 `$strLenBytes` 연산자는 문자열의 길이를 바이트 단위로 결정하는 데 사용됩니다. 이는 문자열 필드의 스토리지 크기를 이해해야 할 때, 특히 문자당 1바이트 이상을 사용할 수 있는 유니코드 문자를 처리할 때 유용합니다.

**파라미터**
+ `expression`: 길이를 계산할 문자열 표현식입니다.

## 예제(MongoDB 쉘)
<a name="strLenBytes-examples"></a>

이 예제에서는 `$strLenBytes` 연산자를 사용하여 문자열 필드의 길이를 바이트 단위로 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
```

**쿼리 예제**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenBytes: "$Desk" }
    }
  }
])
```

**출력**

```
{ "_id" : 1, "Desk" : "Düsseldorf-BVV-021", "length" : 19 }
{ "_id" : 2, "Desk" : "Munich-HGG-32a", "length" : 14 }
{ "_id" : 3, "Desk" : "Cologne-ayu-892.50", "length" : 18 }
{ "_id" : 4, "Desk" : "Dortmund-Hop-78", "length" : 15 }
```

"Düsseldorf-BVV-021" 문자열의 길이는 19바이트이며, 이는 2바이트를 차지하는 유니코드 문자 ""로 인한 코드 포인트(18) 수와 다릅니다.

## 코드 예제
<a name="strLenBytes-code"></a>

`$strLenBytes` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    {
      $project: {
        "Desk": 1,
        "length": { $strLenBytes: "$Desk" }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                "Desk": 1,
                "length": { "$strLenBytes": "$Desk" }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1strLenCP
<a name="strLenCP"></a>

Amazon DocumentDB의 `$strLenCP` 연산자는 코드 포인트(유니코드 문자)의 문자열 표현식 길이를 결정하는 데 사용됩니다. 이는 바이트 수가 아닌 문자열의 문자 수를 알아야 할 때 유용합니다.

**파라미터**
+ `expression`: 코드 포인트의 길이를 반환할 문자열 표현식입니다.

## 예제(MongoDB 쉘)
<a name="strLenCP-examples"></a>

다음 예제에서는 `$strLenCP` 연산자를 사용하여 유니코드 문자가 있는 문자열의 길이를 결정하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
])
```

**쿼리 예제**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenCP: "$Desk" }
    }
  }
])
```

**출력**

```
{ "_id" : 1, "Desk" : "Düsseldorf-BVV-021", "length" : 18 }
{ "_id" : 2, "Desk" : "Munich-HGG-32a", "length" : 14 }
{ "_id" : 3, "Desk" : "Cologne-ayu-892.50", "length" : 18 }
{ "_id" : 4, "Desk" : "Dortmund-Hop-78", "length" : 15 }
```

유니코드 문자(")가 포함된 "Düsseldorf-BVV-021" 문자열의 길이 측정 차이를 확인합니다. `$strLenCP` 연산자는 유니코드 문자 수를 올바르게 계산하고 `$strLenBytes` 연산자는 바이트 수를 계산합니다.

## 코드 예제
<a name="strLenCP-code"></a>

`$strLenCP` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

다음은 MongoDB 드라이버와 함께 Node.js 애플리케이션에서 `$strLenCP` 연산자를 사용하는 예입니다.

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    {
      $project: {
        "Desk": 1,
        "length": { $strLenCP: "$Desk" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

다음은 PyMongo 드라이버와 함께 Python 애플리케이션에서 `$strLenCP` 연산자를 사용하는 예입니다.

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                "Desk": 1,
                "length": { "$strLenCP": "$Desk" }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1strcasecmp
<a name="strcasecmp"></a>

Amazon DocumentDB의 `$strcasecmp` 연산자는 두 문자열 간에 대/소문자를 구분하지 않는 비교를 수행합니다. 두 입력 문자열의 어휘 비교를 나타내는 정수 값을 반환하며 대소문자 차이를 무시합니다.

**파라미터**
+ `string1`: 비교할 첫 번째 문자열입니다.
+ `string2`: 비교할 두 번째 문자열입니다.

## 예제(MongoDB 쉘)
<a name="strcasecmp-examples"></a>

이 예제에서는 연`$strcasecmp`산자를 사용하여 사례 차이를 무시하고 `people` 컬렉션의 데스크 위치 문자열을 비교하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "_id": 1, "Desk": "mke233-wi" },
  { "_id": 2, "Desk": "MKE233-WI" },
  { "_id": 3, "Desk": "mke233-wi" }
]);
```

**쿼리 예제**

```
db.people.aggregate([
  {
    $project: {
      item: 1,
      compare: { $strcasecmp: ["$Desk", "mke233-wi"] }
    }
  }
]);
```

**출력**

```
{ "_id" : 1, "compare" : 0 }
{ "_id" : 2, "compare" : 0 }
{ "_id" : 3, "compare" : 0 }
```

출력은 `&quot;Desk&quot;` 필드와 문자열 간의 비교가 세 문서 모두에 `0` 대해를 `&quot;mke233-wi&quot;` 반환한다는 것을 보여줍니다. 이는 대/소문자를 무시할 때 문자열이 동일함을 나타냅니다.

## 코드 예제
<a name="strcasecmp-code"></a>

`$strcasecmp` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        compare: { $strcasecmp: ["$Desk", "mke233-wi"] }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.people

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'compare': { '$strcasecmp': ['$Desk', 'mke233-wi'] }
            }
        }
    ]))

    print(result)

    client.close()

example()
```

------

# \$1substr
<a name="substr"></a>

Amazon DocumentDB의 `$substr` 연산자는 지정된 문자열에서 하위 문자열을 추출하는 데 사용됩니다. 이는 바이트 범위가 아닌 문자 범위를 기반으로 하위 문자열을 정의해야 하는 경우에 특히 유용합니다. 이는 문자를 나타내는 데 사용되는 바이트 수가 다를 수 있는 유니코드 문자열을 처리할 때 특히 중요합니다.

**파라미터**
+ `string`: 하위 문자열을 추출할 입력 문자열입니다.
+ `start`: 추출할 하위 문자열의 시작 위치(0 기반)입니다. 음수가 아닌 정수 표현식일 수 있습니다.
+ `length`: 추출된 하위 문자열의 문자 수입니다. 음수가 아닌 정수 표현식일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="substr-examples"></a>

이 예제에서는를 사용하여 직원의 사무실 위치에서 상태 약어를 추출`$substr`하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-NRW-021" },
  { "_id": 2, "Desk": "Bremerhaven-HBB-32a" },
  { "_id": 3, "Desk": "Norderstedt-SHH-892.50" },
  { "_id": 4, "Desk": "Brandenburg-BBB-78" }
]);
```

**쿼리 예제**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substr: ["$Desk", 12, 3] }
    }
  }
])
```

**출력**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

## 코드 예제
<a name="substr-code"></a>

`$substr` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function example() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const collection = db.collection("people");

  const result = await collection.aggregate([
    {
      $project: {
        "state": { $substrCP: ["$Desk", 12, 3] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    collection = db["people"]

    result = list(collection.aggregate([
        {
            "$project": {
                "state": { "$substrCP": ["$Desk", 12, 3] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1substrBytes
<a name="substrBytes"></a>

Amazon DocumentDB의 `$substrBytes` 연산자는 지정된 바이트 범위를 기반으로 문자열에서 하위 문자열을 추출하는 데 사용됩니다. 이 연산자는 문자열에서 하위 문자열을 추출해야 할 때 유용하며 문자열의 각 문자를 나타내는 데 필요한 바이트 수가 중요합니다.

유니코드 코드 포인트 수에서 작동하는와 달리 `$substrCP`는 문자열의 문자를 나타내는 데 필요한 바이트 수에서 `$substrBytes` 작동합니다. 비 ASCII 문자가 포함된 문자열을 사용할 때 특히 유용할 수 있습니다. 이러한 문자를 나타내려면 1바이트 이상이 필요할 수 있기 때문입니다.

\$1참고:\$1`$substr`는 버전 3.4 이후 더 이상 사용되지 않습니다. `$substr`는 이제의 별칭입니다`$substrBytes`.

**파라미터**
+ `string`: 하위 문자열을 추출할 입력 문자열입니다.
+ `startByte`: 추출할 하위 문자열의 0 기반 시작 바이트 위치입니다. 음수 값을 사용하여 문자열 끝에서 위치를 지정할 수 있습니다.
+ `length`: 추출할 하위 문자열의 바이트 수입니다.

## 예제(MongoDB 쉘)
<a name="substrBytes-examples"></a>

이 예제에서는 `$substrBytes`를 사용하여 비 ASCII 문자가 포함된 문자열에서 하위 문자열을 추출합니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-NRW-021" },
  { "_id": 2, "Desk": "Bremerhaven-HBB-32a" },
  { "_id": 3, "Desk": "Norderstedt-SHH-892.50" },
  { "_id": 4, "Desk": "Brandenburg-BBB-78" }
]);
```

**쿼리 예제**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrBytes: [ "$Desk", 12, 3] }
    }
  }
])
```

**출력**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

이 예제에서는 `Desk` 필드의 12바이트부터 시작하여 3바이트 하위 문자열을 추출`$substrBytes`하는 데를 사용합니다. 이렇게 하면 문자열에 ASCII가 아닌 문자가 포함될 수 있더라도 2자 상태 약어를 추출할 수 있습니다.

## 코드 예제
<a name="substrBytes-code"></a>

`$substrBytes` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const people = db.collection('people');

  const result = await people.aggregate([
    {
      $project: {
        "state": { $substrBytes: ["$Desk", 12, 3] }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    people = db.people

    result = list(people.aggregate([
        {
            '$project': {
                "state": { '$substrBytes': ["$Desk", 12, 3] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1substrCP
<a name="substrCP"></a>

Amazon DocumentDB의 `$substrCP` 연산자는 문자열에서 하위 문자열을 추출하는 데 사용되며, 여기서 하위 문자열은 UTF-8 코드 포인트(CP)의 범위로 지정됩니다. 이 연산자는 문자의 기본 바이트 표현에 대해 걱정할 필요 없이 하위 문자열을 추출할 수 있으므로 유니코드 문자열로 작업할 때 특히 유용합니다.

바이트 위치에서 작동하는 `$substrBytes` 연산자와 달리 연`$substrCP`산자는 코드 포인트 위치에서 작동합니다. 따라서 코드 포인트 수가 바이트 또는 문자 수와 일치하지 않을 수 있으므로 ASCII가 아닌 문자가 포함된 문자열로 더 쉽게 작업할 수 있습니다.

**파라미터**
+ `string`: 하위 문자열을 추출할 입력 문자열입니다.
+ `start`: 하위 문자열을 추출할 시작 코드 포인트 위치(0 기반)입니다.
+ `length`: 추출할 코드 포인트 수입니다.

## 예제(MongoDB 쉘)
<a name="substrCP-examples"></a>

이 예제에서는 `$substrCP` 연산자를 사용하여 직원의 사무실 위치가 포함된 문자열에서 상태 약어를 추출합니다.

**샘플 문서 생성**

```
db.people.insert([
  { "_id": 1, "first_name": "Jane", "last_name": "Doe", "Desk": "12 Main St, Minneapolis, MN 55401" },
  { "_id": 2, "first_name": "John", "last_name": "Doe", "Desk": "456 Oak Rd, New Orleans, LA 70032" },
  { "_id": 3, "first_name": "Steve", "last_name": "Smith", "Desk": "789 Elm Ln, Bakersfield, CA 93263" }
]);
```

**쿼리 예제**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrCP: ["$Desk", 25, 2] }
    }
  }
]);
```

**출력**

```
{ "_id" : 1, "state" : "MN" }
{ "_id" : 2, "state" : "LA" }
{ "_id" : 3, "state" : "CA" }
```

이 예제에서는 상태 약어가 `Desk` 필드의 25번째 코드 포인트에서 시작되고 2개의 코드 포인트 길이임을 알고 있습니다. `$substrCP` 연산자를 사용하면 문자열의 기본 바이트 표현에 대해 걱정할 필요 없이 상태 약어를 추출할 수 있습니다.

## 코드 예제
<a name="substrCP-code"></a>

`$substrCP` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findStates() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const result = await db.collection('people').aggregate([
    {
      $project: {
        "state": { $substrCP: ["$Desk", 25, 2] }
      }
    }
  ]).toArray();
  console.log(result);
  client.close();
}

findStates();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_states():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    result = list(db.people.aggregate([
        {
            '$project': {
                'state': { '$substrCP': ['$Desk', 25, 2] }
            }
        }
    ]))
    print(result)
    client.close()

find_states()
```

Node.js 및 Python 예제 모두에서 `$substrCP` 연산자를 사용하여 MongoDB Shell 예제와 마찬가지로 `Desk` 필드에서 상태 약어를 추출합니다.

------

# \$1subtract
<a name="subtract"></a>

Amazon DocumentDB의 `$subtract` 연산자는 값을 빼는 데 사용됩니다. 날짜, 숫자 또는 둘의 조합을 빼는 데 사용할 수 있습니다. 이 연산자는 두 날짜 간의 차이를 계산하거나 숫자에서 값을 빼는 데 유용합니다.

**파라미터**
+ `expression1`: 뺄 첫 번째 값입니다.
+ `expression2`:에서 뺄 두 번째 값입니다`<expression1>`.

## 예제(MongoDB 쉘)
<a name="subtract-examples"></a>

다음 예제에서는 `$subtract` 연산자를 사용하여 두 날짜 간의 차이를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.dates.insert([
  {
  "_id": 1,
  "startDate": ISODate("2023-01-01T00:00:00Z"),
  "endDate": ISODate("2023-01-05T12:00:00Z")
  }
]);
```

**쿼리 예제**

```
db.dates.aggregate([
  {
    $project: {
      _id: 1,
      durationDays: {
        $divide: [
          { $subtract: ["$endDate", "$startDate"] },
          1000 * 60 * 60 * 24  // milliseconds in a day
        ]
      }
    }
  }
]);
```

**출력**

```
[ { _id: 1, durationDays: 4.5 } ]
```

이 예제에서는 `$subtract` 연산자를 사용하여 `$endDate`와 일 단위의 차이를 계산`$startDate`합니다.

## 코드 예제
<a name="subtract-code"></a>

`$subtract` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();
    const db = client.db('test');
    const collection = db.collection('dates');

    const pipeline = [
      {
        $project: {
          _id: 1,
          durationDays: {
            $divide: [
              { $subtract: ["$endDate", "$startDate"] },
              1000 * 60 * 60 * 24  // Convert milliseconds to days
            ]
          }
        }
      }
    ];

    const results = await collection.aggregate(pipeline).toArray();

    console.dir(results, { depth: null });

  } finally {
    await client.close();
  }
}

example().catch(console.error);
```

------
#### [ Python ]

```
from datetime import datetime, timedelta
from pymongo import MongoClient

def example():
  
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    try:
        db = client.test
        collection = db.dates

        pipeline = [
            {
                "$project": {
                    "_id": 1,
                    "durationDays": {
                        "$divide": [
                            { "$subtract": ["$endDate", "$startDate"] },
                            1000 * 60 * 60 * 24  # Convert milliseconds to days
                        ]
                    }
                }
            }
        ]

        results = collection.aggregate(pipeline)

        for doc in results:
            print(doc)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        client.close()

example()
```

------

# \$1sum
<a name="sum"></a>

Amazon DocumentDB의 `$sum` 연산자는 그룹의 각 문서에 대해 지정된 표현식의 합계를 반환합니다. 집계 파이프라인의 \$1group 단계에서 일반적으로 합계 계산을 수행하는 데 사용되는 그룹 누적기 연산자입니다.

**파라미터**
+ `expression`: 합계할 숫자 표현식입니다. 필드 경로, 표현식 또는 상수일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="sum-examples"></a>

다음 예제에서는 `$sum` 운영자를 사용하여 각 제품의 총 매출을 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.sales.insertMany([
  { product: "abc", price: 10, quantity: 2 },
  { product: "abc", price: 10, quantity: 3 },
  { product: "xyz", price: 20, quantity: 1 },
  { product: "xyz", price: 20, quantity: 5 }
]);
```

**쿼리 예제**

```
db.sales.aggregate([
  { $group: {
      _id: "$product",
      totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } }
    }}
]);
```

**출력**

```
[
  { "_id": "abc", "totalSales": 50 },
  { "_id": "xyz", "totalSales": 120 }
]
```

## 코드 예제
<a name="sum-code"></a>

`$sum` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('sales');

    const result = await collection.aggregate([
      { $group: {
          _id: "$product",
          totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } }
        }}
    ]).toArray();

    console.log(result);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from pprint import pprint

def example():
    client = None
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

        db = client.test
        collection = db.sales

        result = list(collection.aggregate([
            { '$group': {
                '_id': '$product',
                'totalSales': { '$sum': { '$multiply': [ '$price', '$quantity' ] } }
            }}
        ]))

        pprint(result)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        if client:
            client.close()

example()
```

------

# \$1switch
<a name="switch"></a>

버전 4.0에서 새로 추가되었습니다.

Elastic 클러스터에서는 지원되지 않습니다.

연`$switch`산자는 Amazon DocumentDB의 조건식 연산자로, 사례 표현식 목록을 평가하고 true로 평가되는 첫 번째 사례의 값을 반환하거나 사례 표현식이 true가 아닌 경우 기본값을 반환할 수 있습니다.

**파라미터**
+ `branches`: 각각 평가할 부울 표현식을 포함하는 대/소문자 필드와 대/소문자 표현식이 true인 경우 반환할 값을 포함하는 대/소문자 필드가 있는 문서 배열입니다.
+ `default`: (선택 사항) true인 대소문자 표현식이 없는 경우 반환할 값입니다.

## 예제(MongoDB 쉘)
<a name="switch-examples"></a>

다음 예제에서는 `$switch` 운영자를 사용하여 주문 합계를 기준으로 주문의 배송 비용을 결정하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.orders.insertMany([
  { _id: 1, total: 50 },
  { _id: 2, total: 150 },
  { _id: 3, total: 250 }
]);
```

**쿼리 예제**

```
db.orders.aggregate([
  {
    $project: {
      _id: 1,
      total: 1,
      shippingCost: {
        $switch: {
          branches: [
            { case: { $lte: ["$total", 100] }, then: 5 },
            { case: { $lte: ["$total", 200] }, then: 10 },
            { case: { $gt: ["$total", 200] }, then: 15 }
          ],
          default: 0
        }
      }
    }
  }
])
```

**출력**

```
[
  {
    "_id": 1,
    "total": 50,
    "shippingCost": 5
  },
  {
    "_id": 2,
    "total": 150,
    "shippingCost": 10
  },
  {
    "_id": 3,
    "total": 250,
    "shippingCost": 15
  }
]
```

## 코드 예제
<a name="switch-code"></a>

`$switch` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        total: 1,
        shippingCost: {
          $switch: {
            branches: [
              { case: { $lte: ['$total', 100] }, then: 5 },
              { case: { $lte: ['$total', 200] }, then: 10 },
              { case: { $gt: ['$total', 200] }, then: 15 }
            ],
            default: 0
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.orders

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'total': 1,
                'shippingCost': {
                    '$switch': {
                        'branches': [
                            { 'case': { '$lte': ['$total', 100] }, 'then': 5 },
                            { 'case': { '$lte': ['$total', 200] }, 'then': 10 },
                            { 'case': { '$gt': ['$total', 200] }, 'then': 15 }
                        ],
                        'default': 0
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1toBool
<a name="toBool"></a>

Amazon DocumentDB의 `$toBool` 연산자는 표현식을 부울 값으로 변환합니다.

**파라미터**
+ `expression`: 부울 값으로 변환할 표현식입니다.

**참고**: 모든 문자열은 로 변환됩니다`true`.

## 예제(MongoDB 쉘)
<a name="toBool-examples"></a>

다음 예제에서는 `$toBool` 연산자를 사용하여 다양한 데이터 형식의 디바이스 상태 값을 정규화하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.deviceStates.insertMany([
  { _id: 1, deviceId: "sensor-001", status: true },
  { _id: 2, deviceId: "camera-002", status: 1 },
  { _id: 3, deviceId: "thermostat-003", status: "active" },
  { _id: 4, deviceId: "doorlock-004", status: 0 }
]);
```

**쿼리 예제**

```
db.deviceStates.aggregate([
  {
    $project: {
      _id: 1,
      deviceId: 1,
      isActive: { $toBool: "$status" }
    }
  }
]);
```

**출력**

```
[
  { "_id": 1, "deviceId": "sensor-001", "isActive": true },
  { "_id": 2, "deviceId": "camera-002", "isActive": true },
  { "_id": 3, "deviceId": "thermostat-003", "isActive": true },
  { "_id": 4, "deviceId": "doorlock-004", "isActive": false }
]
```

## 코드 예제
<a name="toBool-code"></a>

`$toBool` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('deviceStates');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        deviceId: 1,
        isActive: { $toBool: '$status' }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['deviceStates']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'deviceId': 1,
                'isActive': { '$toBool': '$status' }
            }
        }
    ]))

    print(result)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1toDate
<a name="toDate"></a>

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$toDate` 집계 연산자는 날짜 또는 날짜 및 시간 문자열을 BSON 날짜 유형으로 변환하는 데 사용됩니다. 연`$dateToString`산자의 역 작업입니다.

**파라미터**
+ `dateString`: BSON 날짜 유형으로 변환할 날짜 또는 날짜 및 시간의 문자열 표현입니다.
+ `format`: (선택 사항) 형식을 지정하는 문자열입니다`dateString`. 제공되지 않은 경우 연산자는 다양한 표준 날짜 및 시간 형식으로 `dateString`를 구문 분석하려고 시도합니다.
+ `timezone`: (선택 사항) 변환에 사용할 시간대를 나타내는 문자열입니다. 제공되지 않은 경우 현지 시간대가 사용됩니다.

## 예제(MongoDB 쉘)
<a name="toDate-examples"></a>

다음 예제에서는 `$toDate` 연산자를 사용하여 날짜 문자열을 BSON 날짜 유형으로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.events.insertMany([
  { _id: 1, eventName: "Mission Start", eventTime: "2023-04-15T10:30:00Z" },
  { _id: 2, eventName: "Checkpoint Reached", eventTime: "2023-04-15T11:15:00Z" },
  { _id: 3, eventName: "Mission End", eventTime: "2023-04-15T12:00:00Z" }
]);
```

**쿼리 예제**

```
db.events.aggregate([
  {
    $project: {
      eventName: 1,
      eventTimeDate: { $toDate: "$eventTime" }
    }
  }
]);
```

**출력**

```
[
  {
    "_id": 1,
    "eventName": "Mission Start",
    "eventTimeDate": ISODate("2023-04-15T10:30:00Z")
  },
  {
    "_id": 2,
    "eventName": "Checkpoint Reached",
    "eventTimeDate": ISODate("2023-04-15T11:15:00Z")
  },
  {
    "_id": 3,
    "eventName": "Mission End",
    "eventTimeDate": ISODate("2023-04-15T12:00:00Z")
  }
]
```

## 코드 예제
<a name="toDate-code"></a>

`$toDate` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  const result = await collection.aggregate([
    {
      $project: {
        eventName: 1,
        eventTimeDate: { $toDate: '$eventTime' }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    result = list(collection.aggregate([
        {
            '$project': {
                'eventName': 1,
                'eventTimeDate': { '$toDate': '$eventTime' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toDecimal
<a name="toDecimal"></a>

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$toDecimal` 연산자는 값을 Decimal128 데이터 형식으로 변환하는 데 사용됩니다. 이는 정확한 십진수 산술을 수행하거나 Double 데이터 유형을 사용하여 정확하게 표현할 수 없는 큰 십진수 값을 처리해야 하는 경우에 유용합니다.

**파라미터**
+ `expression`: Decimal128 데이터 형식으로 변환할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="toDecimal-examples"></a>

이 예제에서는 `$toDecimal` 연산자를 사용하여 문자열 값을 Decimal128 데이터 형식으로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.numbers.insertOne({ _id: 1, value: "3.14" });
db.numbers.insertOne({ _id: 2, value: "2.71" });
```

**쿼리 예제**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    decimalValue: { $toDecimal: "$value" }
  }}
])
```

**출력**

```
[
  { "_id" : 1, "decimalValue" : Decimal128("3.14") },
  { "_id" : 2, "decimalValue" : Decimal128("2.71") }
]
```

## 코드 예제
<a name="toDecimal-code"></a>

`$toDecimal` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      _id: 1,
      decimalValue: { $toDecimal: "$value" }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.numbers

    result = list(collection.aggregate([
        {'$project': {
            '_id': 1,
            'decimalValue': {'$toDecimal': '$value'}
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toDouble
<a name="toDouble"></a>

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$toDouble` 연산자는 값을 이중 정밀도 64비트 부동 소수점 숫자로 변환하는 데 사용됩니다. 이는 원래 숫자 형식이 아닌 값에 대해 산술 연산을 수행해야 할 때 유용할 수 있습니다.

**파라미터**

`&lt;expression&gt;`: 이중 값으로 변환할 표현식입니다. 숫자, 문자열 또는 부울 값으로 확인되는 유효한 표현식일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="toDouble-examples"></a>

이 예제에서는 수학 계산을 수행할 목적으로 `$toDouble` 연산자를 사용하여 문자열 값을 숫자 값으로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.numbers.insertMany([
  { _id: 1, value: "10.5" },
  { _id: 2, value: "20.25" },
  { _id: 3, value: "7" }
])
```

**쿼리 예제**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      value: 1,
      double_value: { $toDouble: "$value" },
      double_plus_five: { $add: [{ $toDouble: "$value" }, 5] }
    }
  }
])
```

**출력**

```
[
  { "_id" : 1, "value" : "10.5", "double_value" : 10.5, "double_plus_five" : 15.5 },
  { "_id" : 2, "value" : "20.25", "double_value" : 20.25, "double_plus_five" : 25.25 },
  { "_id" : 3, "value" : "7", "double_value" : 7.0, "double_plus_five" : 12.0 }
]
```

## 코드 예제
<a name="toDouble-code"></a>

`$toDouble` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        value: 1,
        double_value: { $toDouble: "$value" },
        double_plus_five: { $add: [{ $toDouble: "$value" }, 5] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'value': 1,
                'double_value': { '$toDouble': '$value' },
                'double_plus_five': { '$add': [{ '$toDouble': '$value' }, 5] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toInt
<a name="toInt"></a>

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$toInt` 연산자는 입력 값을 정수 데이터 형식으로 변환하는 데 사용됩니다. 이 연산자는 필드 또는 표현식을 정수로 표현해야 할 때 유용하며, 이는 특정 작업 또는 데이터 처리 작업에 중요할 수 있습니다.

**파라미터**
+ `expression`: 정수로 변환할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="toInt-examples"></a>

다음 예제에서는 `$toInt` 연산자를 사용하여 문자열 값을 정수로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.numbers.insertMany([
  { "name": "one", "value": "1" },
  { "name": "hundred", "value": "100" }
]);
```

**쿼리 예제**

```
db.numbers.aggregate([
  { $project: {
    "_id": 0,
    "name": 1,
    "intValue": { $toInt: "$value" }
  }}
]);
```

**출력**

```
{ "name": "one", "intValue": 1 }
{ "name": "hundred", "intValue": 100 }
```

## 코드 예제
<a name="toInt-code"></a>

`$toInt` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      "_id": 0,
      "name": 1,
      "intValue": { $toInt: "$value" }
    }}
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        { "$project": {
            "_id": 0,
            "name": 1,
            "intValue": { "$toInt": "$value" }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toLong
<a name="toLong"></a>

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$toLong` 연산자는 값을 64비트 정수(긴) 데이터 형식으로 변환하는 데 사용됩니다. 이는 문자열 또는 기타 데이터 형식으로 저장될 수 있는 숫자 값에 대한 산술 연산 또는 비교를 수행해야 할 때 유용할 수 있습니다.

**파라미터**
+ `expression`: 64비트 정수로 변환할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="toLong-examples"></a>

이 예제에서는 `$toLong` 연산자를 사용하여 문자열 값을 64비트 정수로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.numbers.insertMany([
  { _id: 1, value: "42" },
  { _id: 3, value: "9223372036854775807" }
]);
```

**쿼리 예제**

```
db.numbers.aggregate([
  {
    $project: {
      _id: 1,
      longValue: { $toLong: "$value" }
    }
  }
])
```

**출력**

```
[
  { "_id" : 1, "longValue" : 42 },
  { "_id" : 3, "longValue" : 9223372036854775807 }
]
```

## 코드 예제
<a name="toLong-code"></a>

`$toLong` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const numbers = db.collection('numbers');

  const result = await numbers.aggregate([
    {
      $project: {
        _id: 1,
        longValue: { $toLong: "$value" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    numbers = db.numbers

    result = list(numbers.aggregate([
        {
            '$project': {
                '_id': 1,
                'longValue': { '$toLong': '$value' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toLower
<a name="toLower"></a>

Amazon DocumentDB의 `$toLower` 연산자는 문자열을 소문자로 변환하는 데 사용됩니다.

**파라미터**
+ `expression`: 소문자로 변환할 문자열 표현식입니다.

## 예제(MongoDB 쉘)
<a name="toLower-examples"></a>

다음 예제에서는 `$toLower` 연산자를 사용하여 `Desk` 필드를 소문자로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" }
]);
```

**쿼리 예제**

```
db.locations.aggregate([
  { $project: { item: { $toLower: "$Desk" } } }
]);
```

**출력**

```
{ "_id" : 1, "item" : "düsseldorf-bvv-021" }
{ "_id" : 2, "item" : "munich-hgg-32a" }
```

## 코드 예제
<a name="toLower-code"></a>

`$toLower` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function main() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const collection = db.collection("locations");

  const result = await collection.aggregate([
    { $project: { item: { $toLower: "$Desk" } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    collection = db["locations"]

    result = list(collection.aggregate([
        { "$project": { "item": { "$toLower": "$Desk" } } }
    ]))

    print(result)

    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1toObjectId
<a name="toObjectId"></a>

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$toObjectId` 연산자는 ObjectId의 문자열 표현을 실제 ObjectId 데이터 유형으로 변환하는 데 사용됩니다. ObjectIds 데이터 형식이 필요한 작업을 수행할 수 있으므로 ObjectId의 문자열 표현으로 저장된 데이터로 작업할 때 유용할 수 있습니다.

**파라미터**
+ `expression`: 유효한 ObjectId를 나타내는 문자열 표현식입니다.

## 예제(MongoDB 쉘)
<a name="toObjectId-examples"></a>

다음 예제에서는 `$toObjectId` 연산자를 사용하여 ObjectId의 문자열 표현을 ObjectId 데이터 형식으로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.employees.insertMany([
  { _id: 1, empId:"64e5f8886218c620cf0e8f8a", name: "Carol Smith", employeeId: "c720a" },
  { _id: 2, empId:"64e5f94e6218c620cf0e8f8c", name: "Bill Taylor", employeeId: "c721a" }
]);
```

**쿼리 예제**

```
db.employees.aggregate([
  { $project: {
    "empIdAsObjectId": {$toObjectId: "$empId"}}
  }
]);
```

**출력**

```
[
  { _id: 1, empIdAsObjectId: ObjectId('64e5f8886218c620cf0e8f8a') },
  { _id: 2, empIdAsObjectId: ObjectId('64e5f94e6218c620cf0e8f8c') }
]
```

## 코드 예제
<a name="toObjectId-code"></a>

`$toObjectId` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('employees');

  const result = await collection.aggregate([
    { $project: {
      "empIdAsObjectId": {$toObjectId: "$empId"}}
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['employees']

    result = list(collection.aggregate([
      { "$project": {
        "empIdAsObjectId": {"$toObjectId": "$empId"}}
      }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toString
<a name="toString"></a>

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$toString` 연산자는 모든 유형의 값(null 제외)을 문자열 표현으로 변환하는 데 사용됩니다. 이는 원래 문자열 형식이 아닌 값에 대해 문자열 작업을 수행해야 할 때 유용할 수 있습니다.

**파라미터**
+ `expression`: 문자열로 변환할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="toString-examples"></a>

다음 예제에서는 `$toString` 연산자를 사용하여 숫자 값을 문자열로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.numbers.insertMany([
  { "_id": 1, "value": 42 },
  { "_id": 2, "value": 3.14 }
]);
```

**쿼리 예제**

```
db.numbers.aggregate([
  { $project: {
    _id: 1,
    valueAsString: { $toString: "$value" }
  }}
]);
```

**출력**

```
{ "_id": 1, "valueAsString": "42" }
{ "_id": 2, "valueAsString": "3.14" }
```

## 코드 예제
<a name="toString-code"></a>

`$toString` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  const result = await collection.aggregate([
    { $project: {
      _id: 1,
      valueAsString: { $toString: '$value' }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['numbers']

    result = list(collection.aggregate([
        { '$project': {
            '_id': 1,
            'valueAsString': { '$toString': '$value' }
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1toUpper
<a name="toUpper"></a>

Amazon DocumentDB의 `$toUpper` 연산자는 문자열을 대문자로 변환하는 데 사용됩니다.

**파라미터**
+ `expression`: 대문자로 변환할 문자열 표현식입니다.

## 예제(MongoDB 쉘)
<a name="toUpper-examples"></a>

다음 예제에서는 연`$toUpper`산자를 사용하여 `Desk` 필드를 대문자로 변환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.locations.insertMany([
  { "_id": 1, "Desk": "düsseldorf-bvv-021" },
  { "_id": 2, "Desk": "munich-hgg-32a" }
]);
```

**쿼리 예제**

```
db.locations.aggregate([
  { $project: { item: { $toUpper: "$Desk" } } }
]);
```

**출력**

```
{ "_id" : 1, "item" : "DüSSELDORF-BVV-021" }
{ "_id" : 2, "item" : "MUNICH-HGG-32A" }
```

## 코드 예제
<a name="toUpper-code"></a>

`$toUpper` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('locations');

  const result = await collection.aggregate([
    { $project: { item: { $toUpper: '$Desk' } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['locations']

    result = list(collection.aggregate([
        { '$project': { 'item': { '$toUpper': '$Desk' } } }
    ]))

    print(result)

    client.close()

example()
```

------

# \$1trim
<a name="trim"></a>

버전 4.0의 새로운 기능

Amazon DocumentDB의 `$trim` 연산자는 문자열에서 선행 및/또는 후행 공백 문자를 제거하는 데 사용됩니다.

**파라미터**
+ `input`: 잘라낼 문자열 표현식입니다.
+ `chars`: (선택 사항) 입력의 시작과 끝에서 잘라낼 문자를 지정합니다. 기본값은 공백입니다.

## 예제(MongoDB 쉘)
<a name="trim-examples"></a>

다음 예제에서는 `$trim` 연산자를 사용하여 문자열에서 선행 및 후행 공백을 제거하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { "name": "   John Doe   " },
  { "name": "   Bob Johnson   " }
])
```

**쿼리 예제**

```
db.people.aggregate([
  { $project: {
    "name": { $trim: {input: "$name"}}
  }}
])
```

**출력**

```
[
  { "name": "John Doe" },
  { "name": "Bob Johnson" }
]
```

## 코드 예제
<a name="trim-code"></a>

`$trim` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    { $project: {
      "name": { $trim: {input: "$name" }}
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']

    result = list(collection.aggregate([
        {"$project": {
            "name": {"$trim": {"input": "$name"}}
        }}
    ]))

    print(result)
    client.close()

example()
```

------

# \$1type
<a name="type-aggregation"></a>

`$type` 집계 연산자는 지정된 필드의 BSON 데이터 형식을 반환합니다. 이는 집계 작업 중에 필드 값의 데이터 유형을 식별하는 데 유용합니다.

**파라미터**
+ `expression`: 반환할 유형이 있는 필드 또는 표현식입니다.

## 예제(MongoDB 쉘)
<a name="type-aggregation-examples"></a>

다음 예제에서는 `$type` 연산자를 사용하여 각 제품에 대한 가격 필드의 데이터 유형을 식별하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.inventory.insertMany([
  { _id: 1, item: "Notebook", price: 15.99 },
  { _id: 2, item: "Pen", price: "2.50" },
  { _id: 3, item: "Eraser", price: 1 },
  { _id: 4, item: "Ruler", price: null }
]);
```

**쿼리 예제**

```
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      price: 1,
      priceType: { $type: "$price" }
    }
  }
]);
```

**출력**

```
[
  { _id: 1, item: 'Notebook', price: 15.99, priceType: 'double' },
  { _id: 2, item: 'Pen', price: '2.50', priceType: 'string' },
  { _id: 3, item: 'Eraser', price: 1, priceType: 'int' },
  { _id: 4, item: 'Ruler', price: null, priceType: 'null' }
]
```

## 코드 예제
<a name="type-aggregation-code"></a>

`$type` 집계 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.aggregate([
    {
      $project: {
        item: 1,
        price: 1,
        priceType: { $type: "$price" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.aggregate([
        {
            '$project': {
                'item': 1,
                'price': 1,
                'priceType': { '$type': '$price' }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1unset
<a name="unset-stage"></a>

버전 8.0의 새로운 기능

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$unset` 집계 단계를 사용하면 문서에서 필드를 제거할 수 있습니다.

**파라미터**
+ `expression`: 필드 이름 또는 여러 필드 이름의 목록입니다.

## 예제(MongoDB 쉘)
<a name="unset-stage-examples"></a>

다음 예제에서는 `$unset` 집계 단계를 사용하여 `price` 필드를 제거하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.inventory.insertMany([
  { item: "pencil", quantity: 100, price: 0.24},
  { item: "pen", quantity: 204, price: 1.78 }
]);
```

**집계 예제**

```
db.inventory.aggregate([
  {
    $unset: "price"
  }
])
```

**출력**

```
[
  {
    _id: ObjectId('69248951d66dcae121d2950d'),
    item: 'pencil',
    quantity: 100
  },
  {
    _id: ObjectId('69248951d66dcae121d2950e'),
    item: 'pen',
    quantity: 204
  }
]
```

## 코드 예제
<a name="unset-stage-code"></a>

`$unset` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const inventory = db.collection('inventory');

  const result = await inventory.aggregate([
      {
        $unset: "price"
      }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    inventory = db['inventory']

    result = list(inventory.aggregate([
      {
        "$unset": "price"
      }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1unwind
<a name="unwind"></a>

연`$unwind`산자는 입력 문서에서 배열 필드를 분해하여 각 요소에 대한 문서를 출력하는 데 사용됩니다. 이는 데이터 필터링, 정렬 또는 변환과 같은 배열의 개별 요소에 대한 작업을 수행하려는 경우에 유용할 수 있습니다.

**파라미터**
+ `path`: 풀릴 배열 필드의 경로입니다.
+ `includeArrayIndex`: (선택 사항) 배열 요소의 인덱스를 포함할 새 필드의 이름을 지정합니다.
+ `preserveNullAndEmptyArrays`: (선택 사항) 배열 필드가 null이거나 빈 배열일 때 작업이 원본 문서를 유지할지 여부를 결정합니다.

## 예제(MongoDB 쉘)
<a name="unwind-examples"></a>

다음 예제에서는 `$unwind` 연산자를 사용하여 배열 필드를 분해하고 개별 요소에 대해 추가 작업을 수행하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.people.insertMany([
  { _id: 1, name: "jon", hobbies: ["painting", "dancing", "singing"] },
  { _id: 2, name: "jane", hobbies: ["reading", "swimming"] },
  { _id: 3, name: "jack", hobbies: [] }
])
```

**쿼리 예제**

```
db.people.aggregate([
  { $unwind: "$hobbies" }
])
```

**출력**

```
[
  { _id: 1, name: 'jon', hobbies: 'painting' },
  { _id: 1, name: 'jon', hobbies: 'dancing' },
  { _id: 1, name: 'jon', hobbies: 'singing' },
  { _id: 2, name: 'jane', hobbies: 'reading' },
  { _id: 2, name: 'jane', hobbies: 'swimming' }
]
```

## 코드 예제
<a name="unwind-code"></a>

`$unwind` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    { $unwind: '$hobbies' }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']

    result = list(collection.aggregate([
        { '$unwind': '$hobbies' }
    ]))

    print(result)
    client.close()

example()
```

------

# \$1vectorSearch
<a name="vectorSearch"></a>

버전 8.0의 새로운 기능

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$vectorSearch` 연산자를 사용하면 기계 학습에 사용되는 메서드인 벡터 검색을 수행하여 거리 또는 유사성 지표를 사용하여 벡터 표현을 비교하여 유사한 데이터 포인트를 찾을 수 있습니다. 이 기능은 JSON 기반 문서 데이터베이스의 유연성과 풍부한 쿼리를 벡터 검색의 기능과 결합하여 의미 체계 검색, 제품 권장 사항 등과 같은 기계 학습 및 생성형 AI 사용 사례를 구축할 수 있습니다.

**파라미터**
+ `<exact>` (선택 사항): 정확히 가장 가까운 이웃(ENN) 또는 대략적인 가장 가까운 이웃(ANN) 검색을 실행할지 여부를 지정하는 플래그입니다. 값은 다음 중 하나일 수 있습니다.
+ false - ANN 검색을 실행하려면
+ true - ENN 검색을 실행하려면

생략하거나 false로 설정하면 `numCandidates`가 필요합니다.

```
- `<index>` : Name of the Vector Search index to use.
- `<limit>` : Number of documents to return in the results.
- `<numCandidates>` (optional): This field is required if 'exact' is false or omitted. Number of nearest neighbors to use during the search. Value must be less than or equal to (<=) 10000. You can't specify a number less than the number of documents to return ('limit').
- `<path>` : Indexed vector type field to search.
- `<queryVector>` : Array of numbers that represent the query vector.
```

## 예제(MongoDB 쉘)
<a name="vectorSearch-examples"></a>

다음 예제에서는 `$vectorSearch` 연산자를 사용하여 벡터 표현을 기반으로 유사한 제품 설명을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertMany([
  {
    _id: 1,
    name: "Product A",
    description: "A high-quality, eco-friendly product for your home.",
    description_vector: [ 0.2, 0.5, 0.8 ]
  },
  {
    _id: 2,
    name: "Product B",
    description: "An innovative and modern kitchen appliance.",
    description_vector: [0.7, 0.3, 0.9]
  },
  {
    _id: 3,
    name: "Product C",
    description: "A comfortable and stylish piece of furniture.",
    description_vector: [0.1, 0.2, 0.4]
  }
]);
```

**벡터 검색 인덱스 생성**

```
db.runCommand(
    {
        createIndexes: "products",
        indexes: [{
            key: {
                "description_vector": "vector"
            },
            vectorOptions: {
                type: "hnsw",
                dimensions: 3,
                similarity: "cosine",
                m: 16,
                efConstruction: 64
            },
            name: "description_index"
        }]
    }
);
```

**쿼리 예제**

```
db.products.aggregate([
  { $vectorSearch: {
      index: "description_index",
      limit: 2,
      numCandidates: 10,
      path: "description_vector",
      queryVector: [0.1, 0.2, 0.3]
    }
  }
]);
```

**출력**

```
[
  {
    "_id": 1,
    "name": "Product A",
    "description": "A high-quality, eco-friendly product for your home.",
    "description_vector": [ 0.2, 0.5, 0.8 ]
  },
  {
    "_id": 3,
    "name": "Product C",
    "description": "A comfortable and stylish piece of furniture.",
    "description_vector": [ 0.1, 0.2, 0.4 ]
  }
]
```

## 코드 예제
<a name="vectorSearch-code"></a>

`$vectorSearch` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findSimilarProducts(queryVector) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.aggregate([
    { $vectorSearch: {
        index: "description_index",
        limit: 2,
        numCandidates: 10,
        path: "description_vector",
        queryVector: queryVector
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

findSimilarProducts([0.1, 0.2, 0.3]);
```

------
#### [ Python ]

```
from pymongo import MongoClient


def find_similar_products(query_vector):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    result = list(collection.aggregate([
        {
            '$vectorSearch': {
                'index': "description_index",
                'limit': 2,
                'numCandidates': 10,
                'path': "description_vector",
                'queryVector': query_vector
            }
        }
    ]))

    print(result)
    client.close()

find_similar_products([0.1, 0.2, 0.3])
```

------

# \$1week
<a name="week"></a>

Amazon DocumentDB의 `$week` 연산자는 ISO 8601 표준에 따라 날짜의 주 번호(0\$153)를 반환합니다. 주 번호는 연도와 요일을 기준으로 계산되며, 월요일은 해당 주의 첫 번째 날입니다.

**파라미터**

없음

## 예제(MongoDB 쉘)
<a name="week-examples"></a>

다음 예제에서는 `$week` 연산자를 사용하여 지정된 날짜의 주 번호를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.events.insertMany([
  { _id: 1, date: new Date("2023-01-01") },
  { _id: 2, date: new Date("2023-01-08") },
  { _id: 3, date: new Date("2023-12-31") }
]);
```

**쿼리 예제**

```
db.events.aggregate([
  { $project: {
    _id: 1,
    week: { $week: "$date" }
  }}
]);
```

**출력**

```
[
  { "_id": 1, "week": 1 },
  { "_id": 2, "week": 2 },
  { "_id": 3, "week": 53 }
]
```

## 코드 예제
<a name="week-code"></a>

`$week` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const events = db.collection('events');

  const result = await events.aggregate([
    { $project: {
      _id: 1,
      week: { $week: "$date" }
    }}
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
  db = client['test']
  events = db['events']

  result = list(events.aggregate([
      {'$project': {
          '_id': 1,
          'week': {'$week': '$date'}
      }}
  ]))

  print(result)

  client.close()

example()
```

------

# \$1year
<a name="year"></a>

Amazon DocumentDB의 `$year` 연산자는 날짜 또는 타임스탬프에서 연도 구성 요소를 추출합니다.

**파라미터**
+ `expression`: 연도 구성 요소를 추출할 날짜 또는 타임스탬프 표현식입니다.

## 예제(MongoDB 쉘)
<a name="year-examples"></a>

다음 예제에서는 `$year` 연산자를 사용하여 날짜 필드에서 연도 구성 요소를 추출하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.events.insertMany([
  { "_id": 1, "date": ISODate("2023-04-15T00:00:00Z") },
  { "_id": 3, "date": ISODate("2021-12-31T00:00:00Z") }
]);
```

**쿼리 예제**

```
db.events.aggregate([
  { $project: { year: { $year: "$date" } } }
]);
```

**출력**

```
[
  { "_id": 1, "year": 2023 },
  { "_id": 3, "year": 2021 }
]
```

## 코드 예제
<a name="year-code"></a>

`$year` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  const result = await collection.aggregate([
    { $project: { year: { $year: "$date" } } }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    result = list(collection.aggregate([
        {'$project': {'year': {'$year': '$date'}}}
    ]))

    print(result)

    client.close()

example()
```

------

# \$1zip
<a name="zip"></a>

Amazon DocumentDB의 `$zip` 연산자를 사용하면 여러 배열을 단일 튜플 배열(키-값 페어)로 결합할 수 있습니다. 이는 문서 내에서 다양한 소스 또는 배열의 데이터를 결합하여 새 문서 또는 객체를 생성해야 할 때 유용합니다.

**파라미터**
+ `inputs`: 배열로 확인되는 표현식의 배열입니다. 이러한 배열은 단일 튜플 배열로 결합됩니다.
+ `useLongestLength`: (선택 사항) `true`인 경우 출력 배열은 가장 긴 입력 배열의 길이를 가지며 더 짧은 배열을 `null` 값으로 패딩합니다. `false`인 경우 출력 배열은 가장 짧은 입력 배열의 길이를 갖습니다.
+ `defaults`: (선택 사항) 해당 입력 배열이 가장 긴 입력 배열보다 짧고 인 경우 튜플에 사용할 기본값 배열`useLongestLength`입니다`true`.

## 예제(MongoDB 쉘)
<a name="zip-examples"></a>

다음 예제에서는 `$zip` 연산자를 사용하여 두 배열을 단일 튜플 배열로 결합하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.grades.insert([
  {
    "_id": 1,
    "name": "John",
    "scores": [90, 85, 92],
    "classes": ["Math", "English", "Science"]
  },
  {
    "_id": 2,
    "name": "Jane",
    "scores": [88, 91, 90, 85],
    "classes": ["Math", "English", "Science", "History"]
  }
])
```

**쿼리 예제**

```
db.grades.aggregate([
  {
    $project: {
      "name": 1,
      "scoredClasses": {
        $zip: {
          inputs: ["$scores", "$classes"],
          useLongestLength: true,
          defaults: [null, null]
        }
      }
    }
  }
])
```

**출력**

```
[
  {
    "_id": 1,
    "name": "John",
    "scoredClasses": [
      [90, "Math"],
      [85, "English"],
      [92, "Science"],
      [null, null]
    ]
  },
  {
    "_id": 2,
    "name": "Jane",
    "scoredClasses": [
      [88, "Math"],
      [91, "English"],
      [90, "Science"],
      [85, "History"]
    ]
  }
]
```

## 코드 예제
<a name="zip-code"></a>

`$zip` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('grades');

  const result = await collection.aggregate([
    {
      $project: {
        "name": 1,
        "scoredClasses": {
          $zip: {
            inputs: ["$scores", "$classes"],
            useLongestLength: true,
            defaults: [null, null]
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['grades']

    result = list(collection.aggregate([
        {
            '$project': {
                'name': 1,
                'scoredClasses': {
                    '$zip': {
                        'inputs': ['$scores', '$classes'],
                        'useLongestLength': True,
                        'defaults': [None, None]
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------

# Geospatial
<a name="mongo-apis-geospatial-operators"></a>

이 섹션에서는 Amazon DocumentDB에서 지원하는 지리 공간 연산자에 대한 자세한 정보를 제공합니다.

**Topics**
+ [\$1geometry](geometry.md)
+ [\$1geoIntersects](geoIntersects.md)
+ [\$1geoWithin](geoWithin.md)
+ [\$1maxDistance](maxDistance.md)
+ [\$1minDistance](minDistance.md)
+ [\$1near](near.md)
+ [\$1nearSphere](nearSphere.md)

# \$1geometry
<a name="geometry"></a>

Amazon DocumentDB의 `$geometry` 연산자는 지리 공간 쿼리의 일부로 GeoJSON 지오메트리 객체를 지정하는 데 사용됩니다. 이 연산자는 `$geoWithin` 및와 같은 다른 지리 공간 쿼리 연산자와 함께 데이터에 대한 공간 쿼리를 수행하는 `$geoIntersects` 데 사용됩니다.

Amazon DocumentDB에서 `$geometry` 연산자는 다음 GeoJSON 지오메트리 유형을 지원합니다.
+ Point
+ LineString
+ Polygon
+ MultiPoint
+ MultiLineString
+ MultiPolygon
+ GeometryCollection

**파라미터**
+ `type`: GeoJSON 지오메트리 객체의 유형, 예: , `Point` `Polygon`등
+ `coordinates`: 지오메트리를 나타내는 좌표 배열입니다. 좌표 배열의 구조는 지오메트리 유형에 따라 달라집니다.

## 예제(MongoDB 쉘)
<a name="geometry-examples"></a>

다음 예제에서는 `$geometry` 연산자를 사용하여 Amazon DocumentDB에서 `$geoIntersects` 쿼리를 수행하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.locations.insertMany([
  { 
    "_id": 1,
    "name": "Location 1",
    "location": { 
      "type": "Point",
      "coordinates": [-73.983253, 40.753941]
    }
  },
  { 
    "_id": 2,
    "name": "Location 2", 
    "location": {
      "type": "Polygon",
      "coordinates": [[
        [-73.998427, 40.730309],
        [-73.954348, 40.730309],
        [-73.954348, 40.780816],
        [-73.998427, 40.780816],
        [-73.998427, 40.730309]
      ]]
    }
  }
]);
```

**쿼리 예제**

```
db.locations.find({
  "location": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Polygon",
        "coordinates": [[
          [-73.998, 40.730],
          [-73.954, 40.730],
          [-73.954, 40.781],
          [-73.998, 40.781],
          [-73.998, 40.730]
        ]]
      }
    }
  }
})
```

**출력**

```
[
  {
    "_id": 2,
    "name": "Location 2",
    "location": {
      "type": "Polygon",
      "coordinates": [
        [
          [-73.998427, 40.730309],
          [-73.954348, 40.730309],
          [-73.954348, 40.780816],
          [-73.998427, 40.780816],
          [-73.998427, 40.730309]
        ]
      ]
    }
  }
]
```

## 코드 예제
<a name="geometry-code"></a>

`$geometry` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('locations');

  const query = {
    "location": {
      "$geoIntersects": {
        "$geometry": {
          "type": "Polygon",
          "coordinates": [[
            [-73.998, 40.730],
            [-73.954, 40.730],
            [-73.954, 40.781],
            [-73.998, 40.781],
            [-73.998, 40.730]
          ]]
        }
      }
    }
  };

  const result = await collection.find(query).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['locations']

    query = {
        "location": {
            "$geoIntersects": {
                "$geometry": {
                    "type": "Polygon",
                    "coordinates": [[
                        [-73.998, 40.730],
                        [-73.954, 40.730],
                        [-73.954, 40.781],
                        [-73.998, 40.781],
                        [-73.998, 40.730]
                    ]]
                }
            }
        }
    }

    result = list(collection.find(query))
    print(result)

    client.close()

example()
```

------

# \$1geoIntersects
<a name="geoIntersects"></a>

Amazon DocumentDB의 `$geoIntersects` 연산자는 지리 공간 데이터가 지정된 GeoJSON 객체와 교차하는 문서를 찾는 데 사용됩니다. 이 연산자는 다각형 또는 다중 다각형과 같은 지정된 지리적 형태와의 공간 관계를 기반으로 문서를 식별해야 하는 애플리케이션에 유용합니다.

**파라미터**
+ `$geometry`: 교차를 확인할 셰이프를 나타내는 GeoJSON 객체입니다. 지원되는 GeoJSON 객체 유형은 `Point`, `LineString``Polygon`, 및 입니다`MultiPolygon`.

## 예제(MongoDB 쉘)
<a name="geoIntersects-examples"></a>

다음 예제에서는 `$geoIntersects` 연산자를 사용하여 Amazon DocumentDB에서 지정된 좌표 집합의 상태 이름을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.states.insertMany([
  {
    "name": "New York",
    "loc": {
      "type": "Polygon",
      "coordinates": [[
        [-74.25909423828125, 40.47556838210948],
        [-73.70819091796875, 40.47556838210948],
        [-73.70819091796875, 41.31342607582222],
        [-74.25909423828125, 41.31342607582222],
        [-74.25909423828125, 40.47556838210948]
      ]]
    }
  },
  {
    "name": "California",
    "loc": {
      "type": "Polygon",
      "coordinates": [[
        [-124.4091796875, 32.56456771381587],
        [-114.5458984375, 32.56456771381587],
        [-114.5458984375, 42.00964153424558],
        [-124.4091796875, 42.00964153424558],
        [-124.4091796875, 32.56456771381587]
      ]]
    }
  }
]);
```

**쿼리 예제**

```
var location = [-73.965355, 40.782865];

db.states.find({
  "loc": {
    "$geoIntersects": {
      "$geometry": {
        "type": "Point",
        "coordinates": location
      }
    }
  }
}, {
  "name": 1
});
```

**출력**

```
{ "_id" : ObjectId("536b0a143004b15885c91a2c"), "name" : "New York" }
```

## 코드 예제
<a name="geoIntersects-code"></a>

`$geoIntersects` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findStateByGeoIntersects(longitude, latitude) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('states');

  const query = {
    loc: {
      $geoIntersects: {
        $geometry: {
          type: 'Point',
          coordinates: [longitude, latitude]
        }
      }
    }
  };

  const projection = {
    _id: 0,
    name: 1
  };

  const document = await collection.findOne(query, { projection });

  await client.close();
  
  if (document) {
    return document.name;
  } else {
    throw new Error('The geo location you entered was not found in the United States!');
  }
}
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_state_by_geointersects(longitude, latitude):
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        db = client.test
        collection_states = db.states

        query_geointersects = {
            "loc": {
                "$geoIntersects": {
                    "$geometry": {
                        "type": "Point",
                        "coordinates": [longitude, latitude]
                    }
                }
            }
        }

        document = collection_states.find_one(query_geointersects,
                                              projection={
                                                  "_id": 0,
                                                  "name": 1
                                              })
        if document is not None:
            state_name = document['name']
            return state_name
        else:
            raise Exception("The geo location you entered was not found in the United States!")
    except Exception as e:
        print('Exception in geoIntersects: {}'.format(e))
        raise
    finally:
        if client is not None:
            client.close()
```

------

# \$1geoWithin
<a name="geoWithin"></a>

Amazon DocumentDB의 `$geoWithin` 연산자는 위치 데이터(GeoJSON 객체로 표시됨)가 다각형 또는 다중 다각형과 같이 지정된 셰이프 내에 완전히 포함된 문서를 찾는 데 사용됩니다. 이는 특정 지리적 리전 내에 있는 객체를 쿼리하는 데 유용합니다.

**파라미터**
+ `$geometry`: 쿼리할 셰이프를 나타내는 GeoJSON 객체입니다.

## 예제(MongoDB 쉘)
<a name="geoWithin-examples"></a>

다음 예제에서는 `$geoWithin` 운영자를 사용하여 뉴욕 주 내에 있는 모든 공항을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
// Insert state document
db.states.insert({
    "name": "New York",
    "loc": {
        "type": "Polygon",
        "coordinates": [[
            [-79.76278, 45.0],
            [-73.94, 45.0],
            [-73.94, 40.5],
            [-79.76278, 40.5],
            [-79.76278, 45.0]
        ]]
    }
});

// Insert airport documents
db.airports.insert([
    {
        "name": "John F. Kennedy International Airport",
        "type": "airport",
        "code": "JFK",
        "loc": {
            "type": "Point",
            "coordinates": [-73.7781, 40.6413]
        }
    },
    {
        "name": "LaGuardia Airport",
        "type": "airport",
        "code": "LGA",
        "loc": {
            "type": "Point",
            "coordinates": [-73.8772, 40.7769]
        }
    },
    {
        "name": "Buffalo Niagara International Airport",
        "type": "airport",
        "code": "BUF",
        "loc": {
            "type": "Point",
            "coordinates": [-78.7322, 42.9403]
        }
    }
]);
```

**쿼리 예제**

```
var state = db.states.findOne({"name": "New York"});

db.airports.find({
    "loc": {
        "$geoWithin": {
            "$geometry": state.loc
        }
    }
}, {
    "name": 1,
    "type": 1,
    "code": 1,
    "_id": 0
});
```

**출력**

```
[
  {
    "name": "John F. Kennedy International Airport",
    "type": "airport",
    "code": "JFK"
  },
  {
    "name": "LaGuardia Airport",
    "type": "airport",
    "code": "LGA"
  }
]
```

## 코드 예제
<a name="geoWithin-code"></a>

`$geoWithin` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findAirportsWithinState(stateName) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');

  const stateDoc = await db.collection('states').findOne({ name: stateName }, { projection: { _id: 0, loc: 1 } });
  const airportDocs = await db.collection('airports').find({
    loc: {
      $geoWithin: {
        $geometry: stateDoc.loc
      }
    }
  }, { projection: { name: 1, type: 1, code: 1, _id: 0 } }).toArray();

  console.log(airportDocs);

  await client.close();
}

findAirportsWithinState('New York');
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_airports_within_state(state_name):
    try:
        client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
        db = client['test']
        state_doc = db.states.find_one({'name': state_name}, {'_id': 0, 'loc': 1})
        airport_docs = db.airports.find({
            'loc': {
                '$geoWithin': {
                    '$geometry': state_doc['loc']
                }
            }
        }, {'name': 1, 'type': 1, 'code': 1, '_id': 0})
        
        return list(airport_docs)
    except Exception as e:
        print(f'Error: {e}')
    finally:
        client.close()

airports = find_airports_within_state('New York')
print(airports)
```

------

# \$1maxDistance
<a name="maxDistance"></a>

Amazon DocumentDB의 `$maxDistance` 연산자는 문서가 쿼리 결과에 포함되어야 하는 GeoJSON 지점으로부터 최대 거리(미터)를 지정하는 데 사용됩니다. 이 연산자는 `$nearSphere` 연산자와 함께 사용하여 지리 공간 쿼리를 수행합니다.

**파라미터**
+ `$maxDistance`: 문서가 쿼리 결과에 포함되어야 하는 참조 지점과의 최대 거리(미터)입니다.

## 예제(MongoDB 쉘)
<a name="maxDistance-examples"></a>

다음 예제에서는 Amazon DocumentDB에서 `$maxDistance` 연산자를 사용하여 보스턴에서 100킬로미터 이내에 있는 모든 주 수도를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.capitals.insert([
  { state: "Massachusetts", city: "Boston", location: { type: "Point", coordinates: [-71.0589, 42.3601] } },
  { state: "Rhode Island", city: "Providence", location: { type: "Point", coordinates: [-71.4128, 41.8239] } },
  { state: "New Hampshire", city: "Concord", location: { type: "Point", coordinates: [-71.5383, 43.2067] } },
  { state: "Vermont", city: "Montpelier", location: { type: "Point", coordinates: [-72.5751, 44.2604] } }
]);
```

**쿼리 예제**

```
db.capitals.find(
  {
    location: {
      $nearSphere: {
        $geometry: { type: "Point", coordinates: [-71.0589, 42.3601] },
        $maxDistance: 100000
      }
    }
  },
  { state: 1, city: 1, _id: 0 }
);
```

**출력**

```
[
  { "state": "Rhode Island", "city": "Providence" },
  { "state": "New Hampshire", "city": "Concord" }
]
```

## 코드 예제
<a name="maxDistance-code"></a>

`$maxDistance` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findCapitalsNearBoston() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const capitals = db.collection('capitals');

  const result = await capitals.find({
    location: {
      $nearSphere: {
        $geometry: { type: "Point", coordinates: [-71.0589, 42.3601] },
        $maxDistance: 100000
      }
    }
  }, {
    projection: { state: 1, city: 1, _id: 0 }
  }).toArray();

  console.log(result);
  await client.close();
}

findCapitalsNearBoston();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_capitals_near_boston():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    capitals = db.capitals

    result = list(capitals.find(
        {
            "location": {
                "$nearSphere": {
                    "$geometry": { "type": "Point", "coordinates": [-71.0589, 42.3601] },
                    "$maxDistance": 100000
                }
            }
        },
        {"state": 1, "city": 1, "_id": 0}
    ))

    print(result)
    client.close()

find_capitals_near_boston()
```

------

# \$1minDistance
<a name="minDistance"></a>

`$minDistance`는 중심점에서 지정된 최소 거리 이상인 문서를 필터링`$geoNear`하기 위해 `$nearSphere` 또는와 함께 사용되는 찾기 연산자입니다. 이 연산자는 Amazon DocumentDB에서 지원되며 MongoDB의 해당 연산자와 유사하게 작동합니다.

**파라미터**
+ `$minDistance`: 결과에 문서를 포함할 중심점으로부터의 최소 거리(미터)입니다.

## 예제(MongoDB 쉘)
<a name="minDistance-examples"></a>

이 예제에서는 워싱턴주 시애틀의 특정 위치에서 반경 2킬로미터 이내에 있는 모든 레스토랑을 찾습니다.

**샘플 문서 생성**

```
db.usarestaurants.insertMany([
  {
    "state": "Washington",
    "city": "Seattle",
    "name": "Noodle House",
    "rating": 4.8,
    "location": {
      "type": "Point",
      "coordinates": [-122.3517, 47.6159]
    }
  },
  {
    "state": "Washington",
    "city": "Seattle",
    "name": "Pike Place Grill",
    "rating": 4.5,
    "location": {
      "type": "Point",
      "coordinates": [-122.3412, 47.6102]
    }
  },
  {
    "state": "Washington",
    "city": "Bellevue",
    "name": "The Burger Joint",
    "rating": 4.2,
    "location": {
      "type": "Point",
      "coordinates": [-122.2007, 47.6105]
    }
  }
]);
```

**쿼리 예제**

```
db.usarestaurants.find({
  "location": {
    "$nearSphere": {
      "$geometry": {
        "type": "Point",
        "coordinates": [-122.3516, 47.6156]
      },
      "$minDistance": 1,
      "$maxDistance": 2000
    }
  }
}, {
  "name": 1
});
```

**출력**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## 코드 예제
<a name="minDistance-code"></a>

`$minDistance` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findRestaurantsNearby() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('usarestaurants');

  const result = await collection.find({
    "location": {
      "$nearSphere": {
        "$geometry": {
          "type": "Point",
          "coordinates": [-122.3516, 47.6156]
        },
        "$minDistance": 1,
        "$maxDistance": 2000
      }
    }
  }, {
    "projection": { "name": 1 }
  }).toArray();

  console.log(result);
  client.close();
}

findRestaurantsNearby();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_restaurants_nearby():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.usarestaurants

    result = list(collection.find({
        "location": {
            "$nearSphere": {
                "$geometry": {
                    "type": "Point",
                    "coordinates": [-122.3516, 47.6156]
                },
                "$minDistance": 1,
                "$maxDistance": 2000
            }
        }
    }, {
        "projection": {"name": 1}
    }))

    print(result)
    client.close()

find_restaurants_nearby()
```

------

# \$1near
<a name="near"></a>

Amazon DocumentDB의 `$near` 연산자는 지정된 지점에 지리적으로 가까운 문서를 찾는 데 사용됩니다. 거리별로 정렬된 문서를 반환하고 가장 가까운 문서를 먼저 반환합니다. 이 연산자는 2dsphere 지리 공간 인덱스가 필요하며 위치 데이터에 대한 근접 쿼리에 유용합니다.

**파라미터**
+ `$geometry`: 근거리 쿼리의 중심점을 정의하는 GeoJSON Point 객체입니다.
+ `$maxDistance`: (선택 사항) 문서가 쿼리와 일치할 수 있는 지정된 지점으로부터 미터 단위의 최대 거리입니다.
+ `$minDistance`: (선택 사항) 문서가 쿼리와 일치할 수 있는 지정된 지점으로부터 미터 단위의 최소 거리입니다.

**인덱스 요구 사항**
+ `2dsphere index`: GeoJSON Point 데이터에 대한 지리 공간 쿼리에 필요합니다.

## 예제(MongoDB 쉘)
<a name="near-examples"></a>

다음 예제에서는 `$near` 연산자를 사용하여 워싱턴주 시애틀의 특정 위치에 가장 가까운 레스토랑을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.usarestaurants.insert([
  {
    "name": "Noodle House",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.8,
    "location": { "type": "Point", "coordinates": [-122.3517, 47.6159] }
  },
  {
    "name": "Pike Place Grill",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.2,
    "location": { "type": "Point", "coordinates": [-122.3403, 47.6062] }
  },
  {
    "name": "Lola",
    "city": "Seattle",
    "state": "Washington",
    "rating": 4.5,
    "location": { "type": "Point", "coordinates": [-122.3407, 47.6107] }
  }
]);
```

**2Dsphere 인덱스 생성**

```
db.usarestaurants.createIndex({ "location": "2dsphere" });
```

**GeoJSON Point를 사용한 쿼리 예제**

```
db.usarestaurants.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $maxDistance: 100,
      $minDistance: 10
    }
  }
});
```

**출력**

```
{
  "_id" : ObjectId("69031ec9ea1c2922a1ce5f4a"),
  "name" : "Noodle House",
  "city" : "Seattle",
  "state" : "Washington",
  "rating" : 4.8,
  "location" : {
    "type" : "Point",
    "coordinates" : [ -122.3517, 47.6159 ]
  }
}
```

## 코드 예제
<a name="near-code"></a>

`$near` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findNearbyRestaurants() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const restaurants = db.collection('usarestaurants');

  // Create 2dsphere index
  await restaurants.createIndex({ "location": "2dsphere" });

  const result = await restaurants.find({
    location: {
      $near: {
        $geometry: {
          type: "Point",
          coordinates: [-122.3516, 47.6156]
        },
        $maxDistance: 100,
        $minDistance: 10
      }
    }
  }).toArray();

  console.log(result);

  client.close();
}

findNearbyRestaurants();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_nearby_restaurants():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    restaurants = db['usarestaurants']

    # Create 2dsphere index
    restaurants.create_index([("location", "2dsphere")])

    result = list(restaurants.find({
        'location': {
            '$near': {
                '$geometry': {
                    'type': 'Point',
                    'coordinates': [-122.3516, 47.6156]
                },
                '$maxDistance': 100,
                '$minDistance': 10
            }
        }
    }))

    print(result)

    client.close()

find_nearby_restaurants()
```

------

# \$1nearSphere
<a name="nearSphere"></a>

Amazon DocumentDB의 `$nearSphere` 연산자는 지리 공간 지점에서 지정된 거리 내에 있는 문서를 찾는 데 사용됩니다. 이 연산자는 특정 위치의 특정 반경 내에서 모든 레스토랑을 찾는 등 지리 공간 쿼리에 특히 유용합니다.

**파라미터**
+ `$geometry`: 참조 지점을 나타내는 GeoJSON 객체입니다. `type` 및 `coordinates` 필드가 있는 `Point` 객체여야 합니다.
+ `$minDistance`: (선택 사항) 문서가 있어야 하는 참조 지점과의 최소 거리(미터)입니다.
+ `$maxDistance`: (선택 사항) 문서가 있어야 하는 참조 지점과의 최대 거리(미터)입니다.

## 예제(MongoDB 쉘)
<a name="nearSphere-examples"></a>

이 예제에서는 워싱턴주 시애틀의 특정 위치에서 2킬로미터(2,000미터) 이내에 있는 모든 레스토랑을 찾습니다.

**샘플 문서 생성**

```
db.usarestaurants.insert([
  {
    name: "Noodle House",
    location: { type: "Point", coordinates: [-122.3516, 47.6156] }
  },
  {
    name: "Pike Place Grill",
    location: { type: "Point", coordinates: [-122.3403, 47.6101] }
  },
  {
    name: "Seattle Coffee Co.",
    location: { type: "Point", coordinates: [-122.3339, 47.6062] }
  }
]);
```

**쿼리 예제**

```
db.usarestaurants.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-122.3516, 47.6156]
      },
      $minDistance: 1,
      $maxDistance: 2000
    }
  }
}, {
  name: 1
});
```

**출력**

```
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
```

## 코드 예제
<a name="nearSphere-code"></a>

`$nearSphere` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findNearbyRestaurants() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const restaurants = db.collection('usarestaurants');

  const result = await restaurants.find({
    location: {
      $nearSphere: {
        $geometry: {
          type: "Point",
          coordinates: [-122.3516, 47.6156]
        },
        $minDistance: 1,
        $maxDistance: 2000
      }
    }
  }, {
    projection: { name: 1 }
  }).toArray();

  console.log(result);
  client.close();
}

findNearbyRestaurants();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_nearby_restaurants():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    restaurants = db.usarestaurants

    result = list(restaurants.find({
        'location': {
            '$nearSphere': {
                '$geometry': {
                    'type': 'Point',
                    'coordinates': [-122.3516, 47.6156]
                },
                '$minDistance': 1,
                '$maxDistance': 2000
            }
        }
    }, {
        'name': 1
    }))

    print(result)
    client.close()

find_nearby_restaurants()
```

------

# 쿼리 및 프로젝션 연산자
<a name="mongo-apis-query-projection-operators"></a>

이 섹션에서는 Amazon DocumentDB에서 지원하는 쿼리 및 프로젝션 연산자에 대한 자세한 정보를 제공합니다.

**Topics**
+ [\$1](dollar-projection.md)
+ [\$1all](all.md)
+ [\$1and](and.md)
+ [\$1bitsAllClear](bitsAllClear.md)
+ [\$1bitsAllSet](bitsAllSet.md)
+ [\$1bitsAnyClear](bitsAnyClear.md)
+ [\$1bitsAnySet](bitsAnySet.md)
+ [\$1comment](comment.md)
+ [\$1elemMatch](elemMatch.md)
+ [\$1eq](eq.md)
+ [\$1exists](exists.md)
+ [\$1expr](expr.md)
+ [\$1gt](gt.md)
+ [\$1gte](gte.md)
+ [\$1in](in.md)
+ [\$1jsonSchema](jsonSchema.md)
+ [\$1lt](lt.md)
+ [\$1mod](mod-query.md)
+ [\$1lte](lte.md)
+ [\$1meta](meta.md)
+ [\$1ne](ne.md)
+ [\$1nin](nin.md)
+ [\$1nor](nor.md)
+ [\$1not](not.md)
+ [\$1or](or.md)
+ [\$1regex](regex.md)
+ [\$1slice](slice-projection.md)
+ [\$1size](size-query.md)
+ [\$1text](text.md)
+ [\$1type](type.md)

# \$1
<a name="dollar-projection"></a>

`$` 프로젝션 연산자는 쿼리 조건과 일치하는 첫 번째 요소만 반환하도록 배열 필드의 내용을 제한합니다. 일치하는 단일 배열 요소를 프로젝션하는 데 사용됩니다.

**파라미터**
+ `field.$`: 첫 번째 일치 요소를 투영하기 위한 위치 연산자가 있는 배열 필드입니다.

## 예제(MongoDB 쉘)
<a name="dollar-projection-examples"></a>

다음 예제에서는 `$` 프로젝션 연산자를 사용하여 일치하는 배열 요소만 반환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.students.insertMany([
  { _id: 1, name: "Alice", grades: [85, 92, 78, 95] },
  { _id: 2, name: "Bob", grades: [70, 88, 92, 65] },
  { _id: 3, name: "Charlie", grades: [95, 89, 91, 88] }
]);
```

**쿼리 예제**

```
db.students.find(
  { grades: { $gte: 90 } },
  { name: 1, "grades.$": 1 }
);
```

**출력**

```
{ "_id" : 1, "name" : "Alice", "grades" : [ 92 ] }
{ "_id" : 2, "name" : "Bob", "grades" : [ 92 ] }
{ "_id" : 3, "name" : "Charlie", "grades" : [ 95 ] }
```

이 예제에서는 각 학생에 대해 90 이상의 첫 번째 학년만 반환됩니다.

## 코드 예제
<a name="dollar-projection-code"></a>

`$` 프로젝션 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  const result = await collection.find(
    { grades: { $gte: 90 } },
    { projection: { name: 1, "grades.$": 1 } }
  ).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['students']

    result = list(collection.find(
        {'grades': {'$gte': 90}},
        {'name': 1, 'grades.$': 1}
    ))

    print(result)
    client.close()

example()
```

------

# \$1all
<a name="all"></a>

Amazon DocumentDB의 `$all` 연산자는 필드 값이 배열이고 배열의 요소 순서에 관계없이 지정된 모든 요소를 포함하는 문서를 일치시키는 데 사용됩니다.

**파라미터**
+ `field`: 확인할 필드의 이름입니다.
+ `[value1, value2, ...]`: 배열에서 일치시킬 값의 목록입니다.

 

**`$all` 표현식 `$elemMatch` 내에서 사용**

`$all` 표현식 내에서 `$elemMatch` 연산자를 사용하는 것과 관련된 [`$all` 표현식 내에서 `$elemMatch` 사용](functional-differences.md#functional-differences.elemMatch) 제한 사항은 섹션을 참조하세요.

 

**필드 이름의 달러(\$1)**

중첩된 객체에서의 `$` 접두사 필드 쿼리`$all`와 관련된 [필드 이름의 달러(\$1) 및 점(.)](functional-differences.md#functional-differences-dollardot) 제한 사항은 섹션을 참조하세요.

## 예제(MongoDB 쉘)
<a name="all-examples"></a>

다음 예제에서는 "Colors" 필드가 "Red"와 "Blue"가 모두 포함된 배열인 문서를 검색하는 데 `$all` 연산자를 사용하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.example.insertMany([
  { "Item": "Pen", "Colors": ["Red", "Blue", "Green"] },
  { "Item": "Notebook", "Colors": ["Blue", "White"] },
  { "Item": "Poster Paint", "Colors": ["Red", "Yellow", "White"] }
])
```

**쿼리 예제**

```
db.example.find({ "Colors": { $all: ["Red", "Blue"] } }).pretty()
```

**출력**

```
{
  "_id" : ObjectId("6137d6c5b3a1d35e0b6ee6ad"),
  "Item" : "Pen",
  "Colors" : [ 
          "Red", 
          "Blue", 
          "Green" 
  ]
}
```

## 코드 예제
<a name="all-code"></a>

`$all` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  const result = await collection.find({ "Colors": { $all: ["Red", "Blue"] } }).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    result = list(collection.find({ "Colors": { "$all": ["Red", "Blue"] } }))
    print(result)

    client.close()

example()
```

------

# \$1and
<a name="and"></a>

Amazon DocumentDB의 `$and` 연산자는 여러 표현식을 결합하고 단일 조건으로 평가하는 데 사용됩니다. 제공된 모든 표현식이 로 평가`true`되면를 반환하고 `true`그렇지 `false` 않으면를 반환합니다. 이 연산자는 쿼리에 여러 기준을 적용하는 데 유용합니다.

**파라미터**
+ `expression1`: 부울 값으로 평가되는 필수 표현식입니다.
+ `expression2`: 부울 값으로 평가되는 필수 표현식입니다.
+ `...`: 부울 값으로 평가되는 추가 필수 표현식입니다.

## 예제(MongoDB 쉘)
<a name="and-examples"></a>

다음 예제에서는 `$and` 연산자를 사용하여 "사용자" 모음에서 "나이" 필드가 18보다 크고 "상태" 필드가 "활성"인 모든 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { name: "John", age: 25, status: "active" },
  { name: "Jane", age: 17, status: "active" },
  { name: "Bob", age: 30, status: "inactive" },
  { name: "Alice", age: 22, status: "active" }
]);
```

**쿼리 예제**

```
db.users.find({
  $and: [
    { age: { $gt: 18 } },
    { status: "active" }
  ]
});
```

**출력**

```
[
  { "_id" : ObjectId("614e3c4b63f5892e7c4e2345"), "name" : "John", "age" : 25, "status" : "active" },
  { "_id" : ObjectId("614e3c4b63f5892e7c4e2347"), "name" : "Alice", "age" : 22, "status" : "active" }
]
```

## 코드 예제
<a name="and-code"></a>

`$and` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findActiveUsersOlderThan18() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const activeUsersOlderThan18 = await users.find({
    $and: [
      { age: { $gt: 18 } },
      { status: 'active' }
    ]
  }).toArray();

  console.log(activeUsersOlderThan18);
  await client.close();
}

findActiveUsersOlderThan18();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_active_users_older_than_18():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    active_users_older_than_18 = list(users.find({
        '$and': [
            {'age': {'$gt': 18}},
            {'status': 'active'}
        ]
    }))

    print(active_users_older_than_18)
    client.close()

find_active_users_older_than_18()
```

------

# \$1bitsAllClear
<a name="bitsAllClear"></a>

Amazon DocumentDB의 `$bitsAllClear` 연산자는 필드의 지정된 모든 비트가 지워지는 문서와 일치시키는 데 사용됩니다(0으로 설정). 이 연산자는 저장된 데이터에 대해 비트 단위 작업을 수행하는 데 유용할 수 있습니다.

**파라미터**
+ `field`: 지워지는 지정된 비트를 확인할 필드입니다.
+ `value`: 확인할 비트 또는 확인할 비트 위치 목록을 지정하는 숫자 비트 마스크입니다. 숫자 비트마스크는 바이너리(0b...), 십진수, 16진수(0x...), 8진수(0o...) 또는 바이너리(BinData) 형식일 수 있습니다. 비트 위치 목록에서 가장 중요하지 않은 비트의 위치는 0입니다.

## 예제(MongoDB 쉘)
<a name="bitsAllClear-examples"></a>

다음 예제에서는 Amazon DocumentDB에서 `$bitsAllClear` 연산자의 사용을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { _id: 1, bits: 0b1010 },
  { _id: 2, bits: 0b1100 },
  { _id: 3, bits: 0b0101 }
]);
```

**쿼리 예제**

```
db.collection.find({
  bits: { $bitsAllClear: 0b0011 }
})
```

**출력**

```
{ "_id" : 2, "bits" : 12 }
```

쿼리는 비트 마스크에 의해 지정된 모든 비트`0b0011`(가장 중요하지 않은 두 비트)가 `bits` 필드에서 지워지는지 확인합니다. `bits` 필드의 비트가 지워져 있으므로 `_id` 2가 있는 문서는이 조건을 충족합니다.

## 코드 예제
<a name="bitsAllClear-code"></a>

`$bitsAllClear` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.find({
    bits: { $bitsAllClear: 0b0011 }
  }).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['collection']

    result = list(collection.find({
        'bits': { '$bitsAllClear': 0b0011 }
    }))

    print(result)

    client.close()

example()
```

------

# \$1bitsAllSet
<a name="bitsAllSet"></a>

Amazon DocumentDB의 `$bitsAllSet` 연산자는 필드에서 특정 비트 집합이 모두 1로 설정된 문서를 쿼리하는 데 사용됩니다. 이 연산자를 사용하면 필드 값에 대해 비트 단위 작업을 수행할 수 있으며 숫자 값 내에서 개별 비트의 상태를 확인해야 할 때 유용할 수 있습니다.

**파라미터**
+ `field`: 비트 단위 작업을 수행할 숫자 필드의 이름입니다.
+ `value`: 확인할 비트 또는 확인할 비트 위치 목록을 지정하는 숫자 비트 마스크입니다. 숫자 비트마스크는 바이너리(0b...), 십진수, 16진수(0x...), 8진수(0o...) 또는 바이너리(BinData) 형식일 수 있습니다. 비트 위치 목록에서 가장 중요하지 않은 비트의 위치는 0입니다.

## 예제(MongoDB 쉘)
<a name="bitsAllSet-examples"></a>

다음 예제에서는 `$bitsAllSet` 연산자를 사용하여 `flags` 필드에 비트 마스크에 의해 지정된 모든 비트가 설정된 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insert([
  { _id: 1, flags: 0b1010 },
  { _id: 2, flags: 0b1100 },
  { _id: 3, flags: 0b1110 }
])
```

**쿼리 예제**

```
db.collection.find({ flags: { $bitsAllSet: 0b1100 } })
```

**출력**

```
{ "_id": 2, "flags": 12 },
{ "_id": 3, "flags": 14 }
```

이 예제에서 쿼리는 `flags` 필드에 비트 마스크`0b1100`(10진수 값 12를 나타냄)에 의해 지정된 모든 비트가 설정된 문서를 확인합니다. `flags` 필드 값에는 필요한 모든 비트가 설정되어 있으므로(3번째 및 4번째 최소 유효 비트) `_id`2와 3이 있는 문서는이 기준과 일치합니다.

## 코드 예제
<a name="bitsAllSet-code"></a>

`$bitsAllSet` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findWithBitsAllSet() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.find({ flags: { $bitsAllSet: 0b1100 } }).toArray();
  console.log(result);

  await client.close();
}

findWithBitsAllSet();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_with_bits_all_set():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.collection

    result = list(collection.find({ 'flags': { '$bitsAllSet': 0b1100 } }))
    print(result)

    client.close()

find_with_bits_all_set()
```

------

# \$1bitsAnyClear
<a name="bitsAnyClear"></a>

Amazon DocumentDB의 `$bitsAnyClear` 연산자는 필드의 지정된 비트 중 하나가 지워지는 문서와 일치시키는 데 사용됩니다(0으로 설정). 이는 문서에 저장된 필드 값에 대해 비트 단위 작업을 수행하는 데 유용할 수 있습니다.

**파라미터**
+ `field`: 확인할 필드입니다.
+ `value`: 확인할 비트 또는 확인할 비트 위치 목록을 지정하는 숫자 비트 마스크입니다. 숫자 비트마스크는 바이너리(0b...), 십진수, 16진수(0x...), 8진수(0o...) 또는 바이너리(BinData) 형식일 수 있습니다. 비트 위치 목록에서 가장 중요하지 않은 비트의 위치는 0입니다.

## 예제(MongoDB 쉘)
<a name="bitsAnyClear-examples"></a>

다음 예제에서는 `$bitsAnyClear` 연산자를 사용하여 `items` 컬렉션의 `status` 필드에 비트가 명확한지 확인하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.items.insertMany([
  { "_id": 1, "status": 7 },
  { "_id": 2, "status": 15 },
  { "_id": 3, "status": 31 }
]);
```

**쿼리 예제**

```
db.items.find({ "status": { $bitsAnyClear: 8 } })
```

**출력**

```
{ "_id" : 1, "status" : 7 }
```

이 예제에서 쿼리는 `status` 필드가 비트 마스크(이진 )에서 비트 지우기`8`(0)가 있는 문서를 확인합니다`1000`. `status` 값이 `7` (이진 `111`)인 문서는 제공된 비트마스크에서 1비트 이상 지워지기 때문에 쿼리와 일치합니다. 일치하는 클리어 비트는 4번째로 중요하지 않은 비트입니다.

## 코드 예제
<a name="bitsAnyClear-code"></a>

`$bitsAnyClear` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('items');

  const result = await collection.find({ "status": { $bitsAnyClear: 8 } }).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.items

    result = list(collection.find({ "status": { "$bitsAnyClear": 8 } }))
    print(result)

    client.close()

example()
```

------

# \$1bitsAnySet
<a name="bitsAnySet"></a>

Amazon DocumentDB의 `$bitsAnySet` 연산자는 필드의 지정된 비트에서 최소 1비트가 1로 설정된 문서를 쿼리하는 데 사용됩니다. 이 연산자를 사용하면 필드에 저장된 값에 대해 비트 단위 작업을 수행할 수 있으므로 비트 단위 특성을 가진 데이터를 효율적으로 쿼리하고 분석할 수 있습니다.

**파라미터**
+ `field`: 비트 단위 작업을 적용할 필드 이름입니다.
+ `value`: 확인할 비트 또는 확인할 비트 위치 목록을 지정하는 숫자 비트 마스크입니다. 숫자 비트마스크는 바이너리(0b...), 십진수, 16진수(0x...), 8진수(0o...) 또는 바이너리(BinData) 형식일 수 있습니다. 비트 위치 목록에서 가장 중요하지 않은 비트의 위치는 0입니다.

## 예제(MongoDB 쉘)
<a name="bitsAnySet-examples"></a>

다음 예제에서는 연`$bitsAnySet`산자를 사용하여 `flags` 필드에 하나 이상의 비트가 설정된 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { _id: 1, flags: 0b1010 },
  { _id: 2, flags: 0b1100 },
  { _id: 3, flags: 0b0011 },
  { _id: 4, flags: 0b0100 }
]);
```

**쿼리 예제**

```
db.collection.find({
  flags: { $bitsAnySet: 0b1010 }
})
```

**출력**

```
{ "_id" : 1, "flags" : 10 }
{ "_id" : 2, "flags" : 12 }
{ "_id" : 3, "flags" : 3 }
```

쿼리는 비트 마스크에 지정된 비트 중 하나 이상이 `flags` 필드에 `0b1010` 설정된 문서를 반환합니다.

## 코드 예제
<a name="bitsAnySet-code"></a>

`$bitsAnySet` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('collection');

  const result = await collection.find({
    flags: { $bitsAnySet: 0b1010 }
  }).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['collection']

result = list(collection.find({
    'flags': { '$bitsAnySet': 0b1010 }
}))

print(result)

client.close()
```

------

# \$1comment
<a name="comment"></a>

Amazon DocumentDB의 `$comment` 연산자는 쿼리에 설명을 첨부하는 데 사용됩니다. 이는 쿼리에 대한 추가 컨텍스트 또는 정보를 제공하는 데 유용할 수 있으며, 이는 디버깅 또는 문서화 목적에 유용할 수 있습니다. 첨부된 주석은 db.currentOp()와 같은 작업 출력의 일부로 표시됩니다.

**파라미터**
+ `string`: 쿼리에 연결된 설명입니다.

## 예제(MongoDB 쉘)
<a name="comment-examples"></a>

다음 예제에서는 Amazon DocumentDB에서 `$comment` 연산자를 사용하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { name: "John Doe", age: 30, email: "john.doe@example.com" },
  { name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
  { name: "Bob Johnson", age: 35, email: "bob.johnson@example.com" }
]);
```

**쿼리 예제**

```
db.users.find({ age: { $gt: 25 } }, { _id: 0, name: 1, age: 1 }).comment("Retrieve users older than 25");
```

**출력**

```
{ "name" : "John Doe", "age" : 30 }
{ "name" : "Bob Johnson", "age" : 35 }
```

## 코드 예제
<a name="comment-code"></a>

`$comment` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.find({ age: { $gt: 25 } }, { projection: { _id: 0, name: 1, age: 1 } })
                           .comment('Retrieve users older than 25')
                           .toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    users = db.users

    result = list(users.find({ 'age': { '$gt': 25 }}, { '_id': 0, 'name': 1, 'age': 1 })
                .comment('Retrieve users older than 25'))

    print(result)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1elemMatch
<a name="elemMatch"></a>

Amazon DocumentDB의 `$elemMatch` 연산자는 배열 필드를 쿼리하고 배열의 하나 이상의 요소가 지정된 기준과 일치하는 문서를 반환하는 데 사용됩니다. 이 연산자는 중첩 배열 또는 임베디드 문서가 있는 복잡한 데이터 구조가 있는 경우에 특히 유용합니다.

플래너 버전 2.0에에 대한 인덱스 지원이 추가되었습니다`$elemMatch`.

**파라미터**
+ `field`: 쿼리할 배열 필드입니다.
+ `query`: 배열 요소와 일치시킬 기준입니다.

 

**`$all` 표현식 `$elemMatch` 내에서 사용**

`$all` 표현식 내에서 `$elemMatch` 연산자를 사용하는 것과 관련된 [`$all` 표현식 내에서 `$elemMatch` 사용](functional-differences.md#functional-differences.elemMatch) 제한 사항은 섹션을 참조하세요.

## 예제(MongoDB 쉘)
<a name="elemMatch-examples"></a>

다음 예제에서는 `$elemMatch` 연산자를 사용하여 `parts` 배열에 지정된 기준과 일치하는 요소가 하나 이상 있는 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.col.insertMany([
  { _id: 1, parts: [{ part: "xyz", qty: 10 }, { part: "abc", qty: 20 }] },
  { _id: 2, parts: [{ part: "xyz", qty: 5 }, { part: "abc", qty: 10 }] },
  { _id: 3, parts: [{ part: "xyz", qty: 15 }, { part: "abc", qty: 100 }] },
  { _id: 4, parts: [{ part: "abc", qty: 150 }] }
]);
```

**쿼리 예제**

```
db.col.find({
  parts: { "$elemMatch": { part: "xyz", qty: { $lt: 11 } } }
})
```

**출력**

```
{ "_id" : 1, "parts" : [ { "part" : "xyz", "qty" : 10 }, { "part" : "abc", "qty" : 20 } ] }
{ "_id" : 2, "parts" : [ { "part" : "xyz", "qty" : 5 }, { "part" : "abc", "qty" : 10 } ] }
```

## 코드 예제
<a name="elemMatch-code"></a>

`$elemMatch` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const col = db.collection('col');

  const result = await col.find({
    parts: { 
      "$elemMatch": { part: "xyz", qty: { $lt: 11 } } 
    }
  }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    col = db['col']

    result = list(col.find({
      'parts': { 
        '$elemMatch': {'part': 'xyz', 'qty': {'$lt': 11}} 
      }
    }))

    print(result)
    client.close()

example()
```

------

# \$1eq
<a name="eq"></a>

Amazon DocumentDB의 `$eq` 연산자는 필드 값이 지정된 값과 동일한 문서를 일치시키는 데 사용됩니다. 이 연산자는 일반적으로 `find()` 메서드에서 지정된 기준을 충족하는 문서를 검색하는 데 사용됩니다.

**파라미터**
+ `field` : 등식 조건을 확인할 필드입니다.
+ `value` : 필드와 비교할 값입니다.

## 예제(MongoDB 쉘)
<a name="eq-examples"></a>

다음 예제에서는 연`$eq`산자를 사용하여 `name` 필드가와 동일한 모든 문서를 찾는 방법을 보여줍니다`"Thai Curry Palace"`.

**샘플 문서 생성**

```
db.restaurants.insertMany([
  { name: "Thai Curry Palace", cuisine: "Thai", features: ["Private Dining"] },
  { name: "Italian Bistro", cuisine: "Italian", features: ["Outdoor Seating"] },
  { name: "Mexican Grill", cuisine: "Mexican", features: ["Takeout"] }
]);
```

**쿼리 예제**

```
db.restaurants.find({ name: { $eq: "Thai Curry Palace" } });
```

**출력**

```
{ "_id" : ObjectId("68ee586f916df9d39f3d9414"), "name" : "Thai Curry Palace", "cuisine" : "Thai", "features" : [ "Private Dining" ] }
```

## 코드 예제
<a name="eq-code"></a>

`$eq` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findByName(name) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('restaurants');

  const results = await collection.find({ name: { $eq: name } }).toArray();
  console.log(results);

  await client.close();
}

findByName("Thai Curry Palace");
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_by_name(name):
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    collection = db["restaurants"]

    results = list(collection.find({ "name": { "$eq": name } }))
    print(results)

    client.close()

find_by_name("Thai Curry Palace")
```

------

# \$1exists
<a name="exists"></a>

연`$exists`산자는 필드가 문서에 존재하는지 여부를 확인하는 데 사용됩니다. 인덱싱된 필드가 모든 문서에 존재하지 않을 수 있는 Amazon DocumentDB의 희소 인덱스로 작업할 때 `$exists` 특히 유용합니다.

쿼리에서 생성된 희소 인덱스를 사용하려면 인덱스를 포함하는 필드에서 `$exists` 절을 사용해야 합니다. 를 생략하면 `$exists` Amazon DocumentDB는 쿼리에 희소 인덱스를 사용하지 않습니다.

**파라미터**
+ `field`: 존재 여부를 확인할 필드 이름입니다.
+ `value`: 필드가 일치하는 문서에 존재하는지(`true``false`) 또는 존재하지 않는지(`true`) 지정하는 부울 값( 또는 `false`)입니다.

## 예제(MongoDB 쉘)
<a name="exists-examples"></a>

다음 예제에서는 `food` 컬렉션의 `special_diets` 필드에 희소 인덱스가 있는 `$exists` 연산자를 사용하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.food.insertMany([
  { _id: 1, name: "Apple", special_diets: ["vegetarian", "gluten-free"] },
  { _id: 2, name: "Broccoli" },
  { _id: 3, name: "Chicken", special_diets: ["dairy-free"] }
]);
```

**'special\$1diets' 필드에 희소 인덱스 생성**

```
db.food.createIndex({ "special_diets": 1 }, { sparse: true, name: "special_diets_sparse_asc" });
```

**쿼리 예제**

```
db.food.find({ "special_diets": { $exists: true } });
```

**출력**

```
[
  { "_id" : 1, "name" : "Apple", "special_diets" : [ "vegetarian", "gluten-free" ] },
  { "_id" : 3, "name" : "Chicken", "special_diets" : [ "dairy-free" ] }
]
```

## 코드 예제
<a name="exists-code"></a>

`$exists` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('food');

  const result = await collection.find({ "special_diets": { $exists: true } }).toArray();
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
import pymongo

client = pymongo.MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['food']

result = list(collection.find({"special_diets": {"$exists": True}}))
print(result)

client.close()
```

------

# \$1expr
<a name="expr"></a>

버전 4.0의 새 버전입니다.

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$expr` 연산자를 사용하면 쿼리 언어 내에서 집계 표현식을 사용할 수 있습니다. 집계 파이프라인 단계를 사용하는 방식과 마찬가지로 문서 내의 필드에 대해 복잡한 비교 및 계산을 수행할 수 있습니다.

**파라미터**
+ `expression`: 문서 필드에 대해 비교 및 계산을 수행할 수 있도록 부울 값을 반환하는 표현식입니다.

## 예제(MongoDB 쉘)
<a name="expr-examples"></a>

다음 예제에서는 `$expr` 연산자를 사용하여 `manufacturingCost` 필드가 `price` 필드보다 큰 모든 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.inventory.insertMany([
  { item: "abc", manufacturingCost: 500, price: 100 },
  { item: "def", manufacturingCost: 300, price: 450 },
  { item: "ghi", manufacturingCost: 400, price: 120 }
]);
```

**쿼리 예제**

```
db.inventory.find({
  $expr: {
    $gt: ["$manufacturingCost", "$price"]
  }
})
```

**출력**

```
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89a"), "item" : "abc", "manufacturingCost" : 500, "price" : 100 },
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89c"), "item" : "ghi", "manufacturingCost" : 400, "price" : 120 }
```

## 코드 예제
<a name="expr-code"></a>

`$expr` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.find({
    $expr: {
      $gt: ['$manufacturingCost', '$price']
    }
  }).toArray();

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.find({
        '$expr': {
            '$gt': ['$manufacturingCost', '$price']
        }
    }))

    print(result)
    client.close()

example()
```

------

# \$1gt
<a name="gt"></a>

Amazon DocumentDB의 `$gt` 연산자는 지정된 필드의 값이 지정된 값보다 큰 문서를 선택하는 데 사용됩니다. 이 연산자는 수치 비교를 기반으로 데이터를 필터링하고 쿼리하는 데 유용합니다.

**파라미터**
+ `field`: 비교할 필드입니다.
+ `value`: 비교할 값입니다.

## 예제(MongoDB 쉘)
<a name="gt-examples"></a>

다음 예제에서는 `$gt` 연산자를 사용하여 `age` 필드가 30보다 큰 모든 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { name: "John", age: 25 },
  { name: "Jane", age: 32 },
  { name: "Bob", age: 45 },
  { name: "Alice", age: 28 }
]);
```

**쿼리 예제**

```
db.users.find({ age: { $gt: 30 } });
```

**출력**

```
{ "_id" : ObjectId("6249e5c22a5d39884a0a0001"), "name" : "Jane", "age" : 32 },
{ "_id" : ObjectId("6249e5c22a5d39884a0a0002"), "name" : "Bob", "age" : 45 }
```

## 코드 예제
<a name="gt-code"></a>

`$gt` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findUsersOlderThan30() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = await db.collection('users').find({ age: { $gt: 30 } }).toArray();
  console.log(users);
  await client.close();
}

findUsersOlderThan30();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_users_older_than_30():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    users = list(db.users.find({ 'age': { '$gt': 30 } }))
    print(users)
    client.close()

find_users_older_than_30()
```

------

# \$1gte
<a name="gte"></a>

Amazon DocumentDB의 `$gte` 연산자는 지정된 값보다 크거나 같은 값을 일치시키는 데 사용됩니다. 이 연산자는 수치 비교를 기반으로 데이터를 필터링하고 쿼리하는 데 유용합니다.

**파라미터**
+ `field`: 제공된 값과 비교하여 확인할 필드입니다.
+ `value`: 필드와 비교할 값입니다.

## 예제(MongoDB 쉘)
<a name="gte-examples"></a>

다음 예제에서는 Amazon DocumentDB에서 `$gte` 연산자를 사용하여 "나이" 필드가 25보다 크거나 같은 모든 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { _id: 1, name: "John", age: 20 },
  { _id: 2, name: "Jane", age: 25 },
  { _id: 3, name: "Bob", age: 30 },
  { _id: 4, name: "Alice", age: 35 }
]);
```

**쿼리 예제**

```
db.users.find({ age: { $gte: 25 } }, { _id: 0, name: 1, age: 1 });
```

**출력**

```
{ "name" : "Jane", "age" : 25 }
{ "name" : "Bob", "age" : 30 }
{ "name" : "Alice", "age" : 35 }
```

## 코드 예제
<a name="gte-code"></a>

`$gte` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findUsersAboveAge(age) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.find({ age: { $gte: age } }, { projection: { _id: 0, name: 1, age: 1 } }).toArray();
  console.log(result);

  await client.close();
}

findUsersAboveAge(25);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_users_above_age(age):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    users = db.users

    result = list(users.find({ 'age': { '$gte': age } }, { '_id': 0, 'name': 1, 'age': 1 }))
    print(result)

    client.close()

find_users_above_age(25)
```

------

# \$1in
<a name="in"></a>

Amazon DocumentDB의 `$in` 연산자는 필드 값이 배열에 지정된 값과 동일한 문서를 찾을 수 있는 논리적 쿼리 연산자입니다.

**파라미터**
+ `field`: 제공된 배열과 비교하여 확인할 필드입니다.
+ `[value1, value2, ...]`: 지정된 필드와 일치시킬 값의 배열입니다.

 

**필드 이름의 달러(`$`)**

중첩된 객체에서의 `$` 접두사 필드 쿼리`$in`와 관련된 [필드 이름의 달러(\$1) 및 점(.)](functional-differences.md#functional-differences-dollardot) 제한 사항은 섹션을 참조하세요.

## 예제(MongoDB 쉘)
<a name="in-examples"></a>

다음 예제에서는 `$in` 연산자를 사용하여 `color` 필드가 제공된 배열의 값 중 하나인 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.colors.insertMany([
  { "_id": 1, "color": "red" },
  { "_id": 2, "color": "green" },
  { "_id": 3, "color": "blue" },
  { "_id": 4, "color": "yellow" },
  { "_id": 5, "color": "purple" }
])
```

**쿼리 예제**

```
db.colors.find({ "color": { "$in": ["red", "blue", "purple"] } })
```

**출력**

```
{ "_id": 1, "color": "red" },
{ "_id": 3, "color": "blue" },
{ "_id": 5, "color": "purple" }
```

## 코드 예제
<a name="in-code"></a>

`$in` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findByIn() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('colors');

  const result = await collection.find({ "color": { "$in": ["red", "blue", "purple"] } }).toArray();
  console.log(result);

  await client.close();
}

findByIn();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_by_in():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.colors

    result = list(collection.find({ "color": { "$in": ["red", "blue", "purple"] } }))
    print(result)

    client.close()

find_by_in()
```

------

# \$1jsonSchema
<a name="jsonSchema"></a>

버전 4.0의 새 버전입니다.

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$jsonSchema` 연산자는 지정된 JSON 스키마를 기반으로 문서를 필터링하는 데 사용됩니다. 이 연산자를 사용하면 특정 JSON 스키마와 일치하는 문서를 쿼리하여 검색된 문서가 특정 구조 및 데이터 유형 요구 사항을 준수하는지 확인할 수 있습니다.

`$jsonSchema` 평가 쿼리 연산자를 컬렉션 생성의 일부로 사용하여 컬렉션에 삽입되는 문서의 스키마를 검증할 수 있습니다. 추가 정보는 [JSON 스키마 검증 사용](json-schema-validation.md)을 참조하세요.

**파라미터**
+ `required` (배열): 문서의 필수 필드를 지정합니다.
+ `properties` (객체): 문서의 각 필드에 대한 데이터 유형 및 기타 제약 조건을 정의합니다.

## 예제(MongoDB 쉘)
<a name="jsonSchema-examples"></a>

다음 예제에서는 연`$jsonSchema`산자를 사용하여 `name`, `employeeId` 및 `age` 필드가 있고 `employeeId` 필드가 유형인 문서만 검색하도록 `employees` 컬렉션을 필터링하는 방법을 보여줍니다`string`.

**샘플 문서 생성**

```
db.employees.insertMany([
  { "name": { "firstName": "Carol", "lastName": "Smith" }, "employeeId": "1" },
  { "name": { "firstName": "Emily", "lastName": "Brown" }, "employeeId": "2", "age": 25 },
  { "name": { "firstName": "William", "lastName": "Taylor" }, "employeeId": 3, "age": 24 },
  { "name": { "firstName": "Jane", "lastName": "Doe" }, "employeeId": "4" }
]);
```

**쿼리 예제**

```
db.employees.aggregate([
  { $match: {
    $jsonSchema: {
      required: ["name", "employeeId", "age"],
      properties: { "employeeId": { "bsonType": "string" } }
    }
  }}
]);
```

**출력**

```
{ "_id" : ObjectId("6908e8b61f77fc26b2ecd26f"), "name" : { "firstName" : "Emily", "lastName" : "Brown" }, "employeeId" : "2", "age" : 25 }
```

## 코드 예제
<a name="jsonSchema-code"></a>

`$jsonSchema` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function filterByJsonSchema() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('employees');

  const result = await collection.aggregate([
    {
      $match: {
        $jsonSchema: {
          required: ['name', 'employeeId', 'age'],
          properties: { 'employeeId': { 'bsonType': 'string' } }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

filterByJsonSchema();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def filter_by_json_schema():
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
  db = client['test']
  collection = db['employees']

  result = list(collection.aggregate([
    {
      '$match': {
        '$jsonSchema': {
          'required': ['name', 'employeeId', 'age'],
          'properties': {'employeeId': {'bsonType': 'string'}}
        }
      }
    }
  ]))

  print(result)
  client.close()

filter_by_json_schema()
```

------

# \$1lt
<a name="lt"></a>

Amazon DocumentDB의 `$lt` 연산자는 지정된 값보다 작은 값을 일치시키는 데 사용됩니다. 이 연산자는 수치 비교를 기반으로 데이터를 필터링하고 쿼리하는 데 유용합니다.

**파라미터**
+ `field`: 확인할 필드 이름입니다.
+ `value`: 비교할 값입니다.

## 예제(MongoDB 쉘)
<a name="lt-examples"></a>

다음 예제에서는 `$lt` 연산자를 사용하여 `Inventory.OnHand` 값이 50 미만인 문서를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.example.insertMany([
  { "_id": 1, "Inventory": { "OnHand": 25, "Sold": 60 }, "Colors": ["Red", "Blue"] },
  { "_id": 2, "Inventory": { "OnHand": 75, "Sold": 40 }, "Colors": ["Red", "White"] },
  { "_id": 3, "Inventory": { "OnHand": 10, "Sold": 85 }, "Colors": ["Red", "Green"] }
]);
```

**쿼리 예제**

```
db.example.find({ "Inventory.OnHand": { $lt: 50 } })
```

**출력**

```
{ "_id" : 1, "Inventory" : { "OnHand" : 25, "Sold" : 60 }, "Colors" : [ "Red", "Blue" ] }
{ "_id" : 3, "Inventory" : { "OnHand" : 10, "Sold" : 85 }, "Colors" : [ "Red", "Green" ] }
```

## 코드 예제
<a name="lt-code"></a>

`$lt` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  const result = await collection.find({ "Inventory.OnHand": { $lt: 50 } }).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    result = list(collection.find({ "Inventory.OnHand": { "$lt": 50 } }))
    print(result)

    client.close()

example()
```

------

# \$1mod
<a name="mod-query"></a>

`$mod` 쿼리 연산자는 필드 값을 디바이저로 나눈 나머지가 지정된 문서를 선택합니다. 이는 모듈로 산술 조건을 기반으로 문서를 필터링하는 데 유용합니다.

**파라미터**
+ `divisor`: 나눌 숫자입니다.
+ `remainder`: 예상되는 나머지 값입니다.

## 예제(MongoDB 쉘)
<a name="mod-query-examples"></a>

다음 예제에서는 `$mod` 연산자를 사용하여 수량이 홀수인 모든 주문을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.orders.insertMany([
  { _id: 1, item: "Widget", quantity: 15 },
  { _id: 2, item: "Gadget", quantity: 20 },
  { _id: 3, item: "Tool", quantity: 7 },
  { _id: 4, item: "Device", quantity: 12 },
  { _id: 5, item: "Part", quantity: 9 }
]);
```

**쿼리 예제**

```
db.orders.find({ quantity: { $mod: [2, 1] } });
```

**출력**

```
{ "_id" : 1, "item" : "Widget", "quantity" : 15 }
{ "_id" : 3, "item" : "Tool", "quantity" : 7 }
{ "_id" : 5, "item" : "Part", "quantity" : 9 }
```

이 쿼리는 수량을 2로 나눈 나머지 수량이 1인 문서를 반환하여 모든 홀수 수량을 효과적으로 선택합니다.

## 코드 예제
<a name="mod-query-code"></a>

`$mod` 쿼리 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.find({ quantity: { $mod: [2, 1] } }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.find({'quantity': {'$mod': [2, 1]}}))

    print(result)
    client.close()

example()
```

------

# \$1lte
<a name="lte"></a>

Amazon DocumentDB의 `$lte` 연산자는 지정된 필드의 값이 지정된 값보다 작거나 같은 문서를 일치시키는 데 사용됩니다. 이 연산자는 수치 비교를 기반으로 데이터를 필터링하고 쿼리하는 데 유용합니다.

**파라미터**
+ `field`: 비교할 필드입니다.
+ `value`: 비교할 값입니다.

## 예제(MongoDB 쉘)
<a name="lte-examples"></a>

다음 예제에서는 연`$lte`산자를 사용하여 `quantity` 필드가 10 이하인 문서를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.inventory.insertMany([
  { item: "canvas", qty: 100 },
  { item: "paint", qty: 50 },
  { item: "brush", qty: 10 },
  { item: "paper", qty: 5 }
]);
```

**쿼리 예제**

```
db.inventory.find({ qty: { $lte: 10 } });
```

**출력**

```
{ "_id" : ObjectId("..."), "item" : "brush", "qty" : 10 },
{ "_id" : ObjectId("..."), "item" : "paper", "qty" : 5 }
```

## 코드 예제
<a name="lte-code"></a>

`$lte` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require("mongodb");

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db("test");
  const collection = db.collection("inventory");

  const result = await collection.find({ qty: { $lte: 10 } }).toArray();
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client["test"]
    collection = db["inventory"]

    result = list(collection.find({ "qty": { "$lte": 10 } }))
    print(result)

    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1meta
<a name="meta"></a>

`$meta` 연산자는 현재 쿼리 실행과 연결된 메타데이터에 액세스하는 데 사용됩니다. 이 연산자는 주로 텍스트 검색 작업에 사용되며, 메타데이터는 일치하는 문서의 관련성에 대한 정보를 제공할 수 있습니다.

**파라미터**
+ `textScore`: 문서의 텍스트 검색 점수를 검색합니다. 이 점수는 텍스트 검색 쿼리와 문서의 관련성을 나타냅니다.

## 예제(MongoDB 쉘)
<a name="meta-examples"></a>

다음 예제에서는 `$meta` 연산자를 사용하여 텍스트 검색 쿼리와 일치하는 문서의 텍스트 검색 점수를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.documents.insertMany([
  { _id: 1, title: "Coffee Basics", content: "Coffee is a popular beverage made from roasted coffee beans." },
  { _id: 2, title: "Coffee Culture", content: "Coffee coffee coffee - the ultimate guide to coffee brewing and coffee preparation." },
  { _id: 3, title: "Tea vs Coffee", content: "Many people prefer tea over coffee for its health benefits." }
]);
```

**텍스트 인덱스 생성**

```
db.documents.createIndex({ content: "text" });
```

**쿼리 예제**

```
db.documents.find(
  { $text: { $search: "coffee" } },
  { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });
```

**출력**

```
[
  {
    title: 'Coffee Culture',
    content: 'Coffee coffee coffee - the ultimate guide to coffee brewing and coffee preparation.',
    score: 0.8897688388824463
  },
  {
    title: 'Coffee Basics',
    content: 'Coffee is a popular beverage made from roasted coffee beans.',
    score: 0.75990891456604
  },
  {
    title: 'Tea vs Coffee',
    content: 'Many people prefer tea over coffee for its health benefits.',
    score: 0.6079270839691162
  }
]
```

## 코드 예제
<a name="meta-code"></a>

`$meta` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findWithTextScore() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('documents');

  const result = await collection.find(
    { $text: { $search: "coffee" } },
    { projection: { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } } }
  ).sort({ score: { $meta: "textScore" } }).toArray();

  console.log(result);
  client.close();
}

findWithTextScore();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['documents']

for doc in collection.find(
    {'$text': {'$search': 'coffee'}},
    {'_id': 0, 'title': 1, 'content': 1, 'score': {'$meta': 'textScore'}}
).sort([('score', {'$meta': 'textScore'})]):
    print(doc)

client.close()
```

------

# \$1ne
<a name="ne"></a>

연`$ne`산자는 필드 값이 지정된 값과 같지 않은 문서를 일치시키는 데 사용됩니다. 쿼리 조건자에서 문서를 필터링하는 데 사용할 수 있는 비교 연산자입니다.

플래너 버전 2.0에에 대한 인덱스 지원이 추가되었습니다`$ne`.

**파라미터**
+ `field`: 확인할 필드입니다.
+ `value`: 확인할 값입니다.

## 예제(MongoDB 쉘)
<a name="ne-examples"></a>

이 예제에서는 `status` 필드가와 같지 않은 `users` 모음의 모든 문서를 찾습니다`"active"`.

**샘플 문서 생성**

```
db.users.insertMany([
  { name: "John", status: "active" },
  { name: "Jane", status: "inactive" },
  { name: "Bob", status: "suspended" },
  { name: "Alice", status: "active" }
]);
```

**쿼리 예제**

```
db.users.find({ status: { $ne: "active" } });
```

**출력**

```
[
  {
    _id: ObjectId('...'),
    name: 'Jane',
    status: 'inactive'
  },
  {
    _id: ObjectId('...'),
    name: 'Bob',
    status: 'suspended'
  }
]
```

## 코드 예제
<a name="ne-code"></a>

`$ne` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.find({ status: { $ne: 'active' } }).toArray();
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']

result = list(users.find({ 'status': { '$ne': 'active' } }))
print(result)

client.close()
```

------

# \$1nin
<a name="nin"></a>

`$nin` 연산자는 지정된 배열에 없는 값을 일치시키는 데 사용됩니다. 연`$in`산자의 역으로, 지정된 배열에 있는 값과 일치합니다.

플래너 버전 2.0에에 대한 인덱스 지원이 추가되었습니다`$nin`.

**파라미터**
+ `field`: 확인할 필드입니다.
+ `array`: 확인할 값의 배열입니다.

 

**필드 이름의 달러(`$`)**

중첩된 객체에서의 `$` 접두사 필드 쿼리`$nin`와 관련된 [필드 이름의 달러(\$1) 및 점(.)](functional-differences.md#functional-differences-dollardot) 제한 사항은 섹션을 참조하세요.

## 예제(MongoDB 쉘)
<a name="nin-examples"></a>

다음 예제에서는 `$nin` 연산자를 사용하여 `category` 필드가 "Fiction" 또는 "Mystery"와 같지 않은 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.books.insertMany([
  { title: "The Great Gatsby", author: "F. Scott Fitzgerald", category: "Fiction" },
  { title: "To Kill a Mockingbird", author: "Harper Lee", category: "Fiction" },
  { title: "The Girl on the Train", author: "Paula Hawkins", category: "Mystery" },
  { title: "The Martian", author: "Andy Weir", category: "Science Fiction" },
  { title: "The Alchemist", author: "Paulo Coelho", category: "Philosophy" }
])
```

**쿼리 예제**

```
db.books.find({
  category: {
    $nin: ["Fiction", "Mystery"]
  }
})
```

**출력**

```
[
  {
    _id: ObjectId('...'),
    title: 'The Martian',
    author: 'Andy Weir',
    category: 'Science Fiction'
  },
  {
    _id: ObjectId('...'),
    title: 'The Alchemist',
    author: 'Paulo Coelho',
    category: 'Philosophy'
  }
]
```

## 코드 예제
<a name="nin-code"></a>

`$nin` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findBooksNotInCategories(categories) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const books = await db.collection('books').find({
    category: {
      $nin: categories
    }
  }).toArray();
  console.log(books);
  client.close();
}

findBooksNotInCategories(['Fiction', 'Mystery']);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_books_not_in_categories(categories):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    books = list(db.books.find({
        'category': {
            '$nin': categories
        }
    }))
    print(books)
    client.close()

find_books_not_in_categories(['Fiction', 'Mystery'])
```

------

# \$1nor
<a name="nor"></a>

연`$nor`산자는 지정된 쿼리 조건이 true가 아닌 문서를 일치시키는 데 사용됩니다. 논리적 "NOR" 작업과 유사하며, 피연산자가 true가 아니면 결과가 true입니다.

**파라미터**
+ `expression1`: 평가할 첫 번째 표현식입니다.
+ `expression2`: 평가할 두 번째 표현식입니다.
+ `expressionN`: 평가할 추가 표현식입니다.

## 예제(MongoDB 쉘)
<a name="nor-examples"></a>

다음 예제에서는 `qty` 필드가 20 이상이고 `size` 필드가 "XL"이 아닌 문서를 검색하여 `$nor` 연산자의 사용을 보여줍니다.

**샘플 문서 생성**

```
db.items.insertMany([
  { qty: 10, size: "M" },
  { qty: 15, size: "XL" },
  { qty: 25, size: "L" },
  { qty: 30, size: "XL" }
])
```

**쿼리 예제**

```
db.items.find({
  $nor: [
    { qty: { $lt: 20 } },
    { size: "XL" }
  ]
})
```

**출력**

```
[
  { "_id" : ObjectId("..."), "qty" : 25, "size" : "L" }
]
```

## 코드 예제
<a name="nor-code"></a>

`$nor` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('items');

  const result = await collection.find({
    $nor: [
      { qty: { $lt: 20 } },
      { size: "XL" }
    ]
  }).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['items']

    result = list(collection.find({
        '$nor': [
            { 'qty': { '$lt': 20 } },
            { 'size': 'XL' }
        ]
    }))

    print(result)

    client.close()

example()
```

------

# \$1not
<a name="not"></a>

연`$not`산자는 지정된 표현식의 결과를 무효화하는 데 사용됩니다. 지정된 조건이 일치하지 않는 문서를 선택할 수 있습니다.

플래너 버전 2.0에 `$not {eq}` 및에 대한 인덱스 지원이 추가되었습니다`$not {in}`.

**파라미터**
+ `expression`: 부정할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="not-examples"></a>

다음 예제에서는 `$not` 연산자를 사용하여 `status` 필드가 "활성"과 같지 않은 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { name: "John", status: "active" },
  { name: "Jane", status: "inactive" },
  { name: "Bob", status: "pending" },
  { name: "Alice", status: "active" }
]);
```

**쿼리 예제**

```
db.users.find({ status: { $not: { $eq: "active" } } });
```

**출력**

```
[
  {
    _id: ObjectId('...'),
    name: 'Jane',
    status: 'inactive'
  },
  {
    _id: ObjectId('...'),
    name: 'Bob',
    status: 'pending'
  }
]
```

## 코드 예제
<a name="not-code"></a>

`$not` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient, Filters } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.find({
    status: { $not: { $eq: "active" } }
  }).toArray();

  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from bson.son import SON

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['users']

result = collection.find({
    "status": {"$not": {"$eq": "active"}}
})

for doc in result:
    print(doc)

client.close()
```

------

# \$1or
<a name="or"></a>

`$or` 연산자는 두 개 이상의 표현식 배열에서 논리적 OR 작업을 수행하는 데 사용됩니다. 표현식 중 하나 이상과 일치하는 문서를 반환합니다. 이 연산자는 여러 조건 중 하나를 충족하는 문서를 쿼리해야 할 때 유용합니다.

**파라미터**
+ `expression1`: 평가할 첫 번째 표현식입니다.
+ `expression2`: 평가할 두 번째 표현식입니다.
+ `...`: 평가할 추가 표현식(선택 사항).

## 예제(MongoDB 쉘)
<a name="or-examples"></a>

다음 예제에서는 연`$or`산자를 사용하여 `make`가 모델 "Heavy H1"의 "TruckForYou" 또는 모델 "Bolid 1"의 "SportForYou"인 문서를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.cars.insertMany([
  { make: "TruckForYou", model: "Heavy H1", year: 2020 },
  { make: "SportForYou", model: "Bolid 1", year: 2021 },
  { make: "TruckForYou", model: "Cargo 5", year: 2019 },
  { make: "SportForYou", model: "Racer 2", year: 2022 }
]);
```

**쿼리 예제**

```
db.cars.find({
  $or: [
    { make: "TruckForYou", model: "Heavy H1" },
    { make: "SportForYou", model: "Bolid 1" }
  ]
});
```

**출력**

```
[
  {
    _id: ObjectId('...'),
    make: 'TruckForYou',
    model: 'Heavy H1',
    year: 2020
  },
  {
    _id: ObjectId('...'),
    make: 'SportForYou',
    model: 'Bolid 1',
    year: 2021
  }
]
```

## 코드 예제
<a name="or-code"></a>

`$or` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findCarsByMakeModel() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const cars = db.collection('cars');

  const result = await cars.find({
    $or: [
      { make: "TruckForYou", model: "Heavy H1" },
      { make: "SportForYou", model: "Bolid 1" }
    ]
  }).toArray();

  console.log(result);
  client.close();
}

findCarsByMakeModel();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_cars_by_make_model():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    cars = db.cars

    result = list(cars.find({
        '$or': [
            {'make': 'TruckForYou', 'model': 'Heavy H1'},
            {'make': 'SportForYou', 'model': 'Bolid 1'}
        ]
    }))

    print(result)
    client.close()

find_cars_by_make_model()
```

------

# \$1regex
<a name="regex"></a>

`$regex` 연산자를 사용하면 문자열 필드에서 정규식 일치를 수행할 수 있습니다. 복잡한 패턴을 기반으로 문서를 검색하고 필터링하는 강력한 도구입니다.

**파라미터**
+ `regular expression`: 필드와 일치하는 정규식 패턴입니다.
+ `$options`: (선택 사항) 대소문자 구분, 전역 일치 등과 같은 검색 동작을 수정하는 옵션을 제공합니다.

## 예제(MongoDB 쉘)
<a name="regex-examples"></a>

다음 예제에서는 연`$regex`산자를 사용하여 "name" 필드가 특정 패턴과 일치하는 문서를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { name: "John Doe" },
  { name: "Jane Smith" },
  { name: "Alice Johnson" },
  { name: "Bob Williams" },
  { name: "Charlie Davis" }
]);
```

**쿼리 예제**

```
db.users.find({ name: { $regex: /^A/ } })
```

**출력**

```
[
  { "_id" : ObjectId("..."), "name" : "Alice Johnson" }
]
```

이 쿼리는 "이름" 필드가 "A" 문자로 시작하는 모든 문서를 반환합니다.

## 코드 예제
<a name="regex-code"></a>

`$regex` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const results = await collection.find({ name: { $regex: /^A/ } }).toArray();
  console.log(results);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    results = list(collection.find({ 'name': { '$regex': '^A' } }))
    print(results)

    client.close()

if __name__ == "__main__":
    main()
```

------

# \$1slice
<a name="slice-projection"></a>

`$slice` 프로젝션 연산자는 쿼리 결과에 반환되는 배열 요소의 수를 제한합니다. 이를 통해 전체 배열을 로드하지 않고도 배열 필드의 시작 또는 끝에서 특정 수의 요소를 검색할 수 있습니다.

**파라미터**
+ `field`: 프로젝션할 배열 필드입니다.
+ `count`: 반환할 요소 수입니다. 양수 값은 시작에서 요소를 반환하고, 음수 값은 끝에서 반환합니다.

## 예제(MongoDB 쉘)
<a name="slice-projection-examples"></a>

다음 예제에서는 `$slice` 프로젝션 연산자를 사용하여 배열 필드에서 처음 두 항목만 반환하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.inventory.insertMany([
  { _id: 1, item: "notebook", tags: ["office", "school", "supplies", "writing"] },
  { _id: 2, item: "pen", tags: ["office", "writing"] },
  { _id: 3, item: "folder", tags: ["office", "supplies", "storage", "organization"] }
]);
```

**쿼리 예제**

```
db.inventory.find(
  {},
  { item: 1, tags: { $slice: 2 } }
)
```

**출력**

```
{ "_id" : 1, "item" : "notebook", "tags" : [ "office", "school" ] }
{ "_id" : 2, "item" : "pen", "tags" : [ "office", "writing" ] }
{ "_id" : 3, "item" : "folder", "tags" : [ "office", "supplies" ] }
```

## 코드 예제
<a name="slice-projection-code"></a>

`$slice` 프로젝션 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  const result = await collection.find(
    {},
    { projection: { item: 1, tags: { $slice: 2 } } }
  ).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    result = list(collection.find(
        {},
        {'item': 1, 'tags': {'$slice': 2}}
    ))

    print(result)
    client.close()

example()
```

------

# \$1size
<a name="size-query"></a>

`$size` 쿼리 연산자는 배열 필드의 요소 수가 정확히 지정된 문서와 일치합니다. 이는 배열 길이를 기준으로 문서를 필터링하는 데 유용합니다.

**파라미터**
+ `field`: 확인할 배열 필드입니다.
+ `count`: 배열에 포함되어야 하는 정확한 요소 수입니다.

## 예제(MongoDB 쉘)
<a name="size-query-examples"></a>

다음 예제에서는 `$size` 연산자를 사용하여 정확히 세 개의 태그가 있는 모든 제품을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", tags: ["electronics", "computers", "portable"] },
  { _id: 2, name: "Mouse", tags: ["electronics", "accessories"] },
  { _id: 3, name: "Desk", tags: ["furniture", "office", "workspace"] },
  { _id: 4, name: "Monitor", tags: ["electronics"] }
]);
```

**쿼리 예제**

```
db.products.find({ tags: { $size: 3 } });
```

**출력**

```
{ "_id" : 1, "name" : "Laptop", "tags" : [ "electronics", "computers", "portable" ] }
{ "_id" : 3, "name" : "Desk", "tags" : [ "furniture", "office", "workspace" ] }
```

## 코드 예제
<a name="size-query-code"></a>

`$size` 쿼리 연산자를 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.find({ tags: { $size: 3 } }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['products']

    result = list(collection.find({'tags': {'$size': 3}}))

    print(result)
    client.close()

example()
```

------

# \$1text
<a name="text"></a>

`$text` 연산자는 문서 모음 내의 텍스트 인덱스 필드에 대해 전체 텍스트 검색을 수행하는 데 사용됩니다. 이 연산자를 사용하면 특정 단어 또는 문구가 포함된 문서를 검색할 수 있으며, 다른 쿼리 연산자와 결합하여 추가 기준에 따라 결과를 필터링할 수 있습니다.

**파라미터**
+ `$search`: 검색할 텍스트 문자열입니다.

## 예제(MongoDB 쉘)
<a name="text-examples"></a>

다음 예제에서는 `$text` 연산자를 사용하여 "interest"라는 단어가 포함된 문서를 검색하고 "star\$1rating" 필드를 기반으로 결과를 필터링하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.test.insertMany([
  { "_id": 1, "star_rating": 4, "comments": "apple is red" },
  { "_id": 2, "star_rating": 5, "comments": "pie is delicious" },
  { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" },
  { "_id": 4, "star_rating": 2, "comments": "bake the apple pie in the oven" },
  { "_id": 5, "star_rating": 5, "comments": "interesting couch" },
  { "_id": 6, "star_rating": 5, "comments": "interested in couch for sale, year 2022" }
]);
```

**텍스트 인덱스 생성**

```
db.test.createIndex({ comments: "text" });
```

**쿼리 예제**

```
db.test.find({$and: [{star_rating: 5}, {$text: {$search: "interest"}}]})
```

**출력**

```
{ "_id" : 5, "star_rating" : 5, "comments" : "interesting couch" }
{ "_id" : 6, "star_rating" : 5, "comments" : "interested in couch for sale, year 2022" }
```

위의 명령은 모든 형태의 "interest"와 "star\$1rating"이 5인 텍스트 인덱스 필드가 있는 문서를 반환합니다.

## 코드 예제
<a name="text-code"></a>

`$text` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function searchDocuments() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('test');

  const result = await collection.find({
    $and: [
      { star_rating: 5 },
      { $text: { $search: 'interest' } }
    ]
  }).toArray();

  console.log(result);
  client.close();
}

searchDocuments();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def search_documents():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db.test

    result = list(collection.find({
        '$and': [
            {'star_rating': 5},
            {'$text': {'$search': 'interest'}}
        ]
    }))

    print(result)
    client.close()

search_documents()
```

------

# \$1type
<a name="type"></a>

연`$type`산자는 문서에서 필드의 데이터 유형을 확인하는 데 사용됩니다. 유형별 작업 또는 검증이 필요할 때 사용할 수 있습니다. 연`$type`산자는 평가된 표현식의 BSON 유형을 반환합니다. 반환된 유형은 필드 또는 표현식의 유형에 해당하는 문자열입니다.

플래너 버전 2.0에에 대한 인덱스 지원이 추가되었습니다`$type`.

**파라미터**
+ `expression` : 평가할 표현식입니다.

## 예제(MongoDB 쉘)
<a name="type-examples"></a>

**샘플 문서 생성**

```
db.documents.insertMany([
  { _id: 1, name: "John", age: 30, email: "john@example.com" },
  { _id: 2, name: "Jane", age: "25", email: 123456 },
  { _id: 3, name: 123, age: true, email: null }
]);
```

**쿼리 예제**

```
db.documents.find({
  $or: [
    { age: { $type: "number" } },
    { email: { $type: "string" } },
    { name: { $type: "string" } }
  ]
})
```

**출력**

```
[
  { "_id": 1, "name": "John", "age": 30, "email": "john@example.com" },
  { "_id": 2, "name": "Jane", "age": "25", "email": 123456 }
]
```

이 쿼리는 `age` 필드가 "number" 유형이고, `email` 필드가 "string" 유형이고, `name` 필드가 "string" 유형인 문서를 반환합니다.

## 코드 예제
<a name="type-code"></a>

`$type` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findByType() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('documents');

  const results = await collection.find({
    $or: [
      { age: { $type: 'number' } },
      { email: { $type: 'string' } },
      { name: { $type: 'string' } }
    ]
  }).toArray();

  console.log(results);
  client.close();
}

findByType();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_by_type():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['documents']

    results = list(collection.find({
        '$or': [
            {'age': {'$type': 'number'}},
            {'email': {'$type': 'string'}},
            {'name': {'$type': 'string'}}
        ]
    }))

    print(results)
    client.close()

find_by_type()
```

------

# 업데이트 연산자
<a name="mongo-apis-update-operators"></a>

이 섹션에서는 Amazon DocumentDB에서 지원하는 업데이트 연산자에 대한 자세한 정보를 제공합니다.

**Topics**
+ [\$1](dollar-update.md)
+ [\$1[]](dollarBrackets-update.md)
+ [\$1[<identifier>]](dollarIdentifier-update.md)
+ [\$1addToSet](addToSet.md)
+ [\$1bit](bit.md)
+ [\$1currentDate](currentDate.md)
+ [\$1each](each.md)
+ [\$1inc](inc.md)
+ [\$1max](max-update.md)
+ [\$1min](min-update.md)
+ [\$1mul](mul.md)
+ [\$1pop](pop.md)
+ [\$1position](position.md)
+ [\$1pull](pull.md)
+ [\$1pullAll](pullAll.md)
+ [\$1push](push.md)
+ [\$1rename](rename.md)
+ [\$1set](set-update.md)
+ [\$1setOnInsert](setOnInsert.md)
+ [\$1slice](slice-update.md)
+ [\$1sort](sort-update.md)
+ [\$1unset](unset-update.md)

# \$1
<a name="dollar-update"></a>

`$` 위치 연산자는 쿼리 조건과 일치하는 첫 번째 배열 요소를 업데이트합니다. 일치하는 배열 요소의 위치에 대한 자리 표시자 역할을 합니다.

**파라미터**
+ `field.$`: 첫 번째 일치 요소를 업데이트하기 위한 위치 연산자가 있는 배열 필드입니다.

## 예제(MongoDB 쉘)
<a name="dollar-update-examples"></a>

다음 예제에서는 `$` 위치 연산자를 사용하여 특정 배열 요소를 업데이트하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.inventory.insertMany([
  { _id: 1, item: "Widget", quantities: [10, 20, 30] },
  { _id: 2, item: "Gadget", quantities: [5, 15, 25] }
]);
```

**쿼리 예제**

```
db.inventory.updateOne(
  { _id: 1, quantities: 20 },
  { $set: { "quantities.$": 22 } }
);
```

**출력**

```
{
  "_id" : 1,
  "item" : "Widget",
  "quantities" : [ 10, 22, 30 ]
}
```

## 코드 예제
<a name="dollar-update-code"></a>

`$` 위치 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  await collection.updateOne(
    { _id: 1, quantities: 20 },
    { $set: { "quantities.$": 22 } }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.inventory

    collection.update_one(
        {'_id': 1, 'quantities': 20},
        {'$set': {'quantities.$': 22}}
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1[]
<a name="dollarBrackets-update"></a>

`$[]` 모든 위치 연산자는 배열의 모든 요소를 업데이트합니다. 배열 필드의 모든 요소를 수정해야 할 때 사용됩니다.

**파라미터**
+ `field.$[]`: 모든 요소를 업데이트하기 위한 모든 위치 연산자가 있는 배열 필드입니다.

## 예제(MongoDB 쉘)
<a name="dollarBrackets-update-examples"></a>

다음 예제에서는 `$[]` 연산자를 사용하여 모든 배열 요소를 업데이트하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertOne({
  _id: 1,
  name: "Laptop",
  prices: [1000, 1100, 1200]
});
```

**쿼리 예제**

```
db.products.updateOne(
  { _id: 1 },
  { $inc: { "prices.$[]": 50 } }
);
```

**출력**

```
{
  "_id" : 1,
  "name" : "Laptop",
  "prices" : [ 1050, 1150, 1250 ]
}
```

## 코드 예제
<a name="dollarBrackets-update-code"></a>

`$[]` 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  await collection.updateOne(
    { _id: 1 },
    { $inc: { "prices.$[]": 50 } }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    collection.update_one(
        {'_id': 1},
        {'$inc': {'prices.$[]': 50}}
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1[<identifier>]
<a name="dollarIdentifier-update"></a>

`$[<identifier>]` 필터링된 위치 연산자는 지정된 필터 조건과 일치하는 모든 배열 요소를 업데이트합니다. 배열 요소를 선택적으로 업데이트하는 `arrayFilters` 옵션과 함께 사용됩니다.

**파라미터**
+ `field.$[identifier]`: 필터링된 위치 연산자가 있는 배열 필드입니다.
+ `arrayFilters`: 업데이트할 요소를 결정하는 필터 조건 배열입니다.

## 예제(MongoDB 쉘)
<a name="dollarIdentifier-update-examples"></a>

다음 예제에서는 `$[<identifier>]` 연산자를 사용하여 조건을 기반으로 특정 배열 요소를 업데이트하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  grades: [
    { subject: "Math", score: 85 },
    { subject: "Science", score: 92 },
    { subject: "History", score: 78 }
  ]
});
```

**쿼리 예제**

```
db.students.updateOne(
  { _id: 1 },
  { $inc: { "grades.$[elem].score": 5 } },
  { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
);
```

**출력**

```
{
  "_id" : 1,
  "name" : "Alice",
  "grades" : [
    { "subject" : "Math", "score" : 90 },
    { "subject" : "Science", "score" : 97 },
    { "subject" : "History", "score" : 78 }
  ]
}
```

## 코드 예제
<a name="dollarIdentifier-update-code"></a>

`$[<identifier>]` 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  await collection.updateOne(
    { _id: 1 },
    { $inc: { "grades.$[elem].score": 5 } },
    { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.students

    collection.update_one(
        {'_id': 1},
        {'$inc': {'grades.$[elem].score': 5}},
        array_filters=[{'elem.score': {'$gte': 80}}]
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1addToSet
<a name="addToSet"></a>

Amazon DocumentDB의 `$addToSet` 연산자는 값이 배열에 아직 없는 경우에만 배열에 값을 추가하는 데 사용됩니다. 이는 배열에 고유한 요소가 포함되어 있는지 확인하는 데 유용합니다.

**파라미터**
+ `field`: 업데이트할 필드입니다.
+ `value`: 배열 필드에 추가할 값입니다. 단일 값 또는 표현식일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="addToSet-examples"></a>

다음 예제에서는 `$addToSet` 연산자를 사용하여 배열에 고유한 요소를 추가하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertMany([
  { "_id": 1, "item": "apple", "tags": ["fruit", "red", "round"] },
  { "_id": 2, "item": "banana", "tags": ["fruit", "yellow"] },
  { "_id": 3, "item": "cherry", "tags": ["fruit", "red"] }
])
```

**쿼리 예제**

```
db.products.update(
  { "item": "apple" },
  { $addToSet: { "tags": "green" } }
)
```

**출력**

```
{ "_id": 1, "item": "apple", "tags": ["fruit", "red", "round", "green"] }
```

이 예제에서 `$addToSet` 연산자는 문서의 "tags" 배열에 "green" 태그를 추가합니다. 여기서 "item" 필드는 "apple"입니다. "green"이 아직 배열에 없으므로 추가되었습니다.

## 코드 예제
<a name="addToSet-code"></a>

`$addToSet` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  await collection.updateOne(
    { "item": "apple" },
    { $addToSet: { "tags": "green" } }
  );

  const updatedDoc = await collection.findOne({ "item": "apple" });
  console.log(updatedDoc);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    collection.update_one(
        {"item": "apple"},
        {"$addToSet": {"tags": "green"}}
    )

    updated_doc = collection.find_one({"item": "apple"})
    print(updated_doc)

    client.close()

example()
```

------

# \$1bit
<a name="bit"></a>

Amazon DocumentDB의 `$bit` 연산자를 사용하면 지정된 필드의 비트에 대해 비트 단위 작업을 수행할 수 있습니다. 이는 숫자 내에서 개별 비트의 설정, 지우기 또는 상태 확인과 같은 작업에 유용할 수 있습니다.

**파라미터**
+ `field`: 비트 단위 작업을 수행할 필드입니다.
+ `and`: 필드에서 비트 단위 AND 작업을 수행하는 데 사용되는 정수 값입니다.
+ `or`: 필드에서 비트 단위 OR 작업을 수행하는 데 사용되는 정수 값입니다.
+ `xor`: 필드에서 비트 단위 XOR 작업을 수행하는 데 사용되는 정수 값입니다.

## 예제(MongoDB 쉘)
<a name="bit-examples"></a>

다음 예제에서는 `$bit` 연산자를 사용하여 숫자 필드에서 비트 단위 작업을 수행하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.numbers.insert([
  { "_id": 1, "number": 5 },
  { "_id": 2, "number": 12 }
])
```

**쿼리 예제**

```
db.numbers.update(
  { "_id": 1 },
  { "$bit": { "number": { "and": 3 } } }
)
```

**출력**

```
{
  "_id": 1,
  "number": 1
}
```

이 예제에서는 연`$bit`산자를 사용하여가 `_id` 1인 문서의 "숫자" 필드에 대해 비트 단위 AND 작업을 수행합니다. 그 결과 "숫자" 필드의 값이 1로 설정되는데, 이는 원래 값 5와 값 3 사이의 비트 단위 AND 작업의 결과입니다.

## 코드 예제
<a name="bit-code"></a>

`$bit` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('numbers');

  await collection.updateOne(
    { "_id": 1 },
    { "$bit": { "number": { "and": 3 } } }
  );

  const result = await collection.findOne({ "_id": 1 });
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['numbers']

collection.update_one(
    {"_id": 1},
    {"$bit": {"number": {"and": 3}}}
)

result = collection.find_one({"_id": 1})
print(result)

client.close()
```

------

# \$1currentDate
<a name="currentDate"></a>

`$currentDate` 연산자는 필드 값을 현재 날짜 및 시간으로 설정하는 데 사용됩니다. 이 연산자는 문서가 삽입되거나 업데이트될 때 현재 타임스탬프로 필드를 자동으로 업데이트하는 데 유용합니다.

**파라미터**
+ `field`: 현재 날짜 및 시간으로 업데이트할 필드입니다.
+ `type`: (선택 사항) 현재 날짜에 사용할 BSON 유형을 지정합니다. `date` 또는 `timestamp`입니다.

## 예제(MongoDB 쉘)
<a name="currentDate-examples"></a>

다음 예제에서는 `$currentDate` 연산자를 사용하여 `lastModified` 필드를 새 문서가 삽입된 현재 날짜 및 시간으로 설정하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insert({
  name: "John Doe",
  email: "john.doe@example.com"
})
```

**쿼리 예제**

```
db.users.updateOne(
  { name: "John Doe" },
  { $currentDate: { lastModified: true } }
)
```

**업데이트된 문서 보기**

```
db.users.findOne({ name: "John Doe" })
```

**출력**

```
{
  _id: ObjectId('...'),
  name: 'John Doe',
  email: 'john.doe@example.com',
  lastModified: ISODate('2025-10-25T22:50:29.963Z')
}
```

## 코드 예제
<a name="currentDate-code"></a>

`$currentDate` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateUserWithCurrentDate() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  await users.updateOne(
    { name: 'John Doe' },
    { $currentDate: { lastModified: true } }
  );

  console.log('User updated with current date');
  client.close();
}

updateUserWithCurrentDate();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_user_with_current_date():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db.users

    result = users.update_one(
        {'name': 'John Doe'},
        {'$currentDate': {'lastModified': True}}
    )

    print('User updated with current date')
    client.close()

update_user_with_current_date()
```

------

# \$1each
<a name="each"></a>

연`$each`산자는 `$push` 및와 같은 다른 업데이트 연산자와 함께 사용하여 배열 필드에 여러 값을 `$addToSet`추가합니다. 여러 업데이트 작업을 실행할 필요 없이 단일 작업으로 배열에 여러 요소를 추가할 수 있습니다.

**파라미터**
+ `value`: 배열 필드에 추가할 값의 배열입니다.

## 예제(MongoDB 쉘)
<a name="each-examples"></a>

다음 예제에서는 `$each` 연산자와 함께 `$push` 연산자를 사용하여 배열 필드에 여러 요소를 추가하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.fruits.insertOne({
  _id: 1,
  fruits: ["apple", "banana"]
})
```

**쿼리 예제**

```
db.fruits.updateOne(
  { _id: 1 },
  { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
)
```

**업데이트된 문서 보기**

```
db.fruits.findOne({ _id: 1 })
```

**출력**

```
{
  _id: 1,
  fruits: [ 'apple', 'banana', 'cherry', 'durian', 'elderberry' ]
}
```

## 코드 예제
<a name="each-code"></a>

`$each` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('fruits');

  await collection.updateOne(
    { _id: 1 },
    { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
  );

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['fruits']

    collection.update_one(
        {'_id': 1},
        {'$push': {'fruits': {'$each': ['cherry', 'durian', 'elderberry']}}}
    )

    client.close()

example()
```

------

# \$1inc
<a name="inc"></a>

`$inc` 연산자는 필드 값을 지정된 양만큼 늘리는 데 사용됩니다. 현재 값을 검색하고 새 값을 계산한 다음 필드를 업데이트할 필요 없이 카운터 또는 등급과 같은 숫자 필드를 업데이트하는 데 사용됩니다.

**파라미터**
+ `field`: 늘릴 필드의 이름입니다.
+ `amount`: 필드를 늘릴 양입니다. 양수 또는 음수 값일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="inc-examples"></a>

다음 예제에서는 `$inc` 연산자를 사용하여 문서의 `age` 필드를 늘리는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertOne({_id: 123, name: "John Doe", age: 30})
```

**쿼리 예제**

```
db.users.updateOne({_id: 123}, {$inc: {age: 1}})
```

**업데이트된 문서 보기**

```
db.users.findOne({_id: 123})
```

**출력**

```
{ "_id" : 123, "name" : "John Doe", "age" : 31 }
```

## 코드 예제
<a name="inc-code"></a>

`$inc` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateWithInc() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.updateOne(
    { _id: 123 },
    { $inc: { age: 1 } }
  );

  console.log(result);

  await client.close();
}

updateWithInc();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_with_inc():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    result = collection.update_one(
        {'_id': 123},
        {'$inc': {'age': 1}}
    )

    print(result.modified_count)

    client.close()

update_with_inc()
```

------

# \$1max
<a name="max-update"></a>

`$max` 업데이트 연산자는 지정된 값이 현재 필드 값보다 큰 경우에만 필드 값을 업데이트합니다. 이 연산자는 업데이트 전반에서 최대값을 유지하는 데 유용합니다.

**파라미터**
+ `field`: 업데이트할 필드입니다.
+ `value`: 현재 필드 값과 비교할 값입니다.

## 예제(MongoDB 쉘)
<a name="max-update-examples"></a>

다음 예제에서는 `$max` 연산자를 사용하여 플레이어의 기록된 최고 점수를 업데이트하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.scores.insertMany([
  { _id: 1, player: "Alice", highScore: 85 },
  { _id: 2, player: "Bob", highScore: 92 },
  { _id: 3, player: "Charlie", highScore: 78 }
])
```

**업데이트 예제**

```
db.scores.updateOne(
  { _id: 1 },
  { $max: { highScore: 95 } }
)
```

**결과**

Alice의 `highScore` 필드는 95가 현재 값인 85보다 크므로 95로 업데이트됩니다.

```
{ "_id": 1, "player": "Alice", "highScore": 95 }
```

## 코드 예제
<a name="max-update-code"></a>

`$max` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('scores');

  const result = await collection.updateOne(
    { _id: 1 },
    { $max: { highScore: 95 } }
  );

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['scores']

    result = collection.update_one(
        { '_id': 1 },
        { '$max': { 'highScore': 95 } }
    )

    print(result)
    client.close()

example()
```

------

# \$1min
<a name="min-update"></a>

`$min` 업데이트 연산자는 지정된 값이 현재 필드 값보다 작은 경우에만 필드 값을 업데이트합니다. 이 연산자는 업데이트 전반에 걸쳐 최소값을 유지하는 데 유용합니다.

**파라미터**
+ `field`: 업데이트할 필드입니다.
+ `value`: 현재 필드 값과 비교할 값입니다.

## 예제(MongoDB 쉘)
<a name="min-update-examples"></a>

다음 예제에서는 `$min` 연산자를 사용하여 기상 관측소의 기록된 최저 온도를 업데이트하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.weather.insertMany([
  { _id: 1, station: "Station A", lowestTemp: 15 },
  { _id: 2, station: "Station B", lowestTemp: 20 },
  { _id: 3, station: "Station C", lowestTemp: 18 }
])
```

**업데이트 예제**

```
db.weather.updateOne(
  { _id: 1 },
  { $min: { lowestTemp: 12 } }
)
```

**결과**

12가 현재 값인 15보다 작기 때문에 스테이션 A의 `lowestTemp` 필드가 12로 업데이트됩니다.

```
{ "_id": 1, "station": "Station A", "lowestTemp": 12 }
```

## 코드 예제
<a name="min-update-code"></a>

`$min` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('weather');

  const result = await collection.updateOne(
    { _id: 1 },
    { $min: { lowestTemp: 12 } }
  );

  console.log(result);
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['weather']

    result = collection.update_one(
        { '_id': 1 },
        { '$min': { 'lowestTemp': 12 } }
    )

    print(result)
    client.close()

example()
```

------

# \$1mul
<a name="mul"></a>

Amazon DocumentDB의 `$mul` 연산자는 필드 값에 지정된 숫자를 곱하는 데 사용됩니다. 이는 신용 카드 상태에 따라 비행 거리를 업데이트하는 등 여러 문서를 원자적이고 일관되게 업데이트하는 데 유용할 수 있습니다.

**파라미터**
+ `field`: 곱할 필드입니다.
+ `multiplier`: 필드 값에 곱할 숫자입니다.

## 예제(MongoDB 쉘)
<a name="mul-examples"></a>

이 예제에서는 `$mul` 연산자를 사용하여 `credit_card` 필드가 인 모든 문서의 `flight_miles` 값을 두 배로 늘리는 방법을 보여줍니다`true`.

**샘플 문서 생성**

```
db.miles.insertMany([
  { "_id": 1, "member_since": new Date("1987-01-01"), "credit_card": false, "flight_miles": [1205, 2560, 880] },
  { "_id": 2, "member_since": new Date("1982-01-01"), "credit_card": true, "flight_miles": [2410, 5120, 1780, 5560] },
  { "_id": 3, "member_since": new Date("1999-01-01"), "credit_card": true, "flight_miles": [2410, 1760] }
]);
```

**쿼리 예제**

```
db.miles.update(
  { "credit_card": { "$eq": true } },
  { "$mul": { "flight_miles.$[]": NumberInt(2) } },
  { "multi": true }
);
```

**출력**

```
{ "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ] }
{ "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 4820, 10240, 3560, 11120 ] }
{ "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 4820, 3520 ] }
```

신용 카드가 있는 고객의 경우 비행 마일이 두 배로 늘어났습니다.

`$[]` 위치 배열 연산자는 `flight_miles` 배열의 각 요소에 `$mul` 작업을 적용하는 데 사용됩니다.

## 코드 예제
<a name="mul-code"></a>

`$mul` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateFlightMiles() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  await collection.updateMany(
    { credit_card: true },
    { $mul: { 'flight_miles.$[]': 2 } }
  );

  const documents = await collection.find().toArray();
  console.log(documents);

  await client.close();
}

updateFlightMiles();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_flight_miles():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.miles

    collection.update_many(
        {'credit_card': True},
        {'$mul': {'flight_miles.$[]': 2}}
    )

    documents = list(collection.find())
    print(documents)

    client.close()

update_flight_miles()
```

------

# \$1pop
<a name="pop"></a>

Amazon DocumentDB의 `$pop` 연산자는 배열 필드에서 첫 번째 또는 마지막 요소를 제거하는 데 사용됩니다. 고정 크기 배열을 유지하거나 문서 내에서 대기열과 같은 데이터 구조를 구현해야 할 때 특히 유용합니다.

**파라미터**
+ `field`: 요소를 제거할 배열 필드의 이름입니다.
+ `value`: 제거할 요소의 위치를 결정하는 정수 값입니다. 값이 이면 마지막 요소가 `1` 제거되고 값이 이면 첫 번째 요소가 `-1` 제거됩니다.

## 예제(MongoDB 쉘)
<a name="pop-examples"></a>

이 예제에서는 `$pop` 연산자를 사용하여 배열 필드에서 첫 번째 및 마지막 요소를 제거하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insertMany([
  { "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming", "hiking"] },
  { "_id": 2, "name": "Jane Smith", "hobbies": ["cooking", "gardening", "painting"] }
])
```

**쿼리 예제**

```
// Remove the first element from the "hobbies" array
db.users.update({ "_id": 1 }, { $pop: { "hobbies": -1 } })

// Remove the last element from the "hobbies" array
db.users.update({ "_id": 2 }, { $pop: { "hobbies": 1 } })
```

**출력**

```
{ "_id" : 1, "name" : "John Doe", "hobbies" : [ "swimming", "hiking" ] }
{ "_id" : 2, "name" : "Jane Smith", "hobbies" : [ "cooking", "gardening" ] }
```

## 코드 예제
<a name="pop-code"></a>

`$pop` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  // Remove the first element from the "hobbies" array
  await collection.updateOne({ "_id": 1 }, { $pop: { "hobbies": -1 } });

  // Remove the last element from the "hobbies" array
  await collection.updateOne({ "_id": 2 }, { $pop: { "hobbies": 1 } });

  const users = await collection.find().toArray();
  console.log(users);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    # Remove the first element from the "hobbies" array
    collection.update_one({"_id": 1}, {"$pop": {"hobbies": -1}})

    # Remove the last element from the "hobbies" array
    collection.update_one({"_id": 2}, {"$pop": {"hobbies": 1}})

    users = list(collection.find())
    print(users)

    client.close()

example()
```

------

# \$1position
<a name="position"></a>

Amazon DocumentDB의 `$position` 한정자는 `$push` 연산자가 요소를 삽입하는 배열의 위치를 지정합니다. `$position` 한정자가 없으면 `$push` 연산자가 배열 끝에 요소를 삽입합니다.

**파라미터**
+ `field`: 업데이트할 배열 필드입니다.
+ `num`: 제로 기반 인덱싱을 기반으로 요소를 삽입해야 하는 배열의 위치입니다.

**참고**: `$position` 한정자를 사용하려면 `$each` 한정자와 함께 표시되어야 합니다.

## 예제(MongoDB 쉘)
<a name="position-examples"></a>

다음 예제에서는 `$position` 연산자를 사용하여 프로젝트 관리 시스템의 특정 위치에 작업을 삽입하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.projects.insertOne({ "_id": 1, "name": "Website Redesign", "tasks": ["Design mockups"] })
```

**쿼리 예제 1 - 시작 부분에 긴급 작업 추가**

```
db.projects.updateOne(
   { _id: 1 },
   {
     $push: {
        tasks: {
           $each: ["Security audit", "Performance review"],
           $position: 0
        }
     }
   }
)
```

**출력 1**

```
{ "_id": 1, "name": "Website Redesign", "tasks": ["Security audit", "Performance review", "Design mockups"] }
```

**쿼리 예제 2 - 특정 위치에 작업 추가**

```
db.projects.insertOne({ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Deploy to store"] })

db.projects.updateOne(
   { _id: 2 },
   {
     $push: {
        tasks: {
           $each: ["Code review", "Testing phase"],
           $position: 2
        }
     }
   }
)
```

**출력 2**

```
{ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Code review", "Testing phase", "Deploy to store"] }
```

## 코드 예제
<a name="position-code"></a>

`$position` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function insertTasksAtPosition() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('projects');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        tasks: {
          $each: ["Security audit", "Performance review"],
          $position: 0
        }
      }
    }
  );

  const updatedProject = await collection.findOne({ _id: 1 });
  console.log(updatedProject);

  await client.close();
}

insertTasksAtPosition();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def insert_tasks_at_position():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['projects']

    result = collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'tasks': {
                    '$each': ['Security audit', 'Performance review'],
                    '$position': 0
                }
            }
        }
    )

    updated_project = collection.find_one({'_id': 1})
    print(updated_project)

    client.close()

insert_tasks_at_position()
```

------

# \$1pull
<a name="pull"></a>

`$pull` 연산자는 배열에서 지정된 조건과 일치하는 값 또는 값의 모든 인스턴스를 제거하는 데 사용됩니다. 이 연산자는 문서 내의 배열 필드에서 특정 요소를 제거해야 할 때 유용합니다.

**파라미터**
+ `field`: 값을 제거할 배열 필드의 이름입니다().
+ `value`: 배열에서 제거할 요소(들)를 결정하는 값 또는 조건입니다.

## 예제(MongoDB 쉘)
<a name="pull-examples"></a>

다음 예제에서는 `$pull` 연산자를 사용하여 배열 필드에서 요소를 제거하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.restaurants.insertMany([
  {
    name: "Pizza Hut",
    cuisine: "Italian",
    features: ["Delivery", "Takeout", "Dine-in"]
  },
  {
    name: "Sushi Saito",
    cuisine: "Japanese",
    features: ["Dine-in", "Private Dining"]
  },
  {
    name: "Taco Bell",
    cuisine: "Mexican",
    features: ["Delivery", "Takeout", "Drive-thru"]
  }
])
```

**쿼리 예제**

```
db.restaurants.updateMany(
  { cuisine: "Italian" },
  { $pull: { features: "Takeout" } }
)
```

**출력**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

위의 쿼리는 `cuisine` 필드가 "이탈리아어"인 모든 문서에서 "Takeout" 기능을 제거합니다.

## 코드 예제
<a name="pull-code"></a>

`$pull` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateRestaurants() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const restaurants = db.collection('restaurants');

  await restaurants.updateMany(
    { cuisine: 'Italian' },
    { $pull: { features: 'Takeout' } }
  );

  const updatedRestaurants = await restaurants.find({}).toArray();
  console.log(updatedRestaurants);

  await client.close();
}

updateRestaurants();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_restaurants():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    restaurants = db.restaurants

    result = restaurants.update_many(
        { 'cuisine': 'Italian' },
        { '$pull': { 'features': 'Takeout' } }
    )

    updated_restaurants = list(restaurants.find({}))
    print(updated_restaurants)

    client.close()

update_restaurants()
```

------

# \$1pullAll
<a name="pullAll"></a>

Amazon DocumentDB의 `$pullAll` 연산자는 배열 필드에서 지정된 값의 모든 인스턴스를 제거하는 데 사용됩니다. 이는 단일 작업으로 배열에서 여러 요소를 제거해야 하는 경우에 특히 유용합니다.

**파라미터**
+ `field`: 요소를 제거할 배열 필드의 이름입니다.
+ `value`: 배열 필드에서 제거할 값의 배열입니다.

## 예제(MongoDB 쉘)
<a name="pullAll-examples"></a>

다음 예제에서는 `$pullAll` 연산자를 사용하여 배열 필드에서 여러 요소를 제거하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.restaurants.insert([
  {
    "name": "Taj Mahal",
    "cuisine": "Indian",
    "features": ["Private Dining", "Live Music"]
  },
  {
    "name": "Golden Palace",
    "cuisine": "Chinese",
    "features": ["Private Dining", "Takeout"]
  },
  {
    "name": "Olive Garden",
    "cuisine": "Italian",
    "features": ["Private Dining", "Outdoor Seating"]
  }
])
```

**쿼리 예제**

```
db.restaurants.update(
  { "name": "Taj Mahal" },
  { $pullAll: { "features": ["Private Dining", "Live Music"] } }
)
```

**출력**

```
{
  "name": "Taj Mahal",
  "cuisine": "Indian",
  "features": []
}
```

## 코드 예제
<a name="pullAll-code"></a>

`$pullAll` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('restaurants');

  await collection.updateMany(
    { "name": "Taj Mahal" },
    { $pullAll: { "features": ["Private Dining", "Live Music"] } }
  );

  const updatedDocument = await collection.findOne({ "name": "Taj Mahal" });
  console.log(updatedDocument);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['restaurants']

    collection.update_many(
        {"name": "Taj Mahal"},
        {"$pullAll": {"features": ["Private Dining", "Live Music"]}}
    )

    updated_document = collection.find_one({"name": "Taj Mahal"})
    print(updated_document)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1push
<a name="push"></a>

Amazon DocumentDB의 `$push` 연산자는 문서의 배열 필드에 항목을 추가하는 데 사용됩니다. 이 연산자는 전체 배열을 덮어쓰지 않고 기존 배열에 새 데이터를 추가해야 하는 경우에 특히 유용합니다.

**파라미터**
+ `field`: 새 요소를 추가해야 하는 배열 필드의 이름입니다.
+ `value`: 배열에 추가할 값입니다.
+ `position`: (선택 사항) 새 요소를 추가해야 하는 배열의 위치를 지정하는 한정자입니다. 지원되는 한정자는 `$` (배열 끝에 추가) 및 `$[]` (배열 끝에 추가, 배열 필터 무시)입니다.

## 예제(MongoDB 쉘)
<a name="push-examples"></a>

다음 예제에서는 `$push` 연산자를 사용하여 문서의 배열 필드에 새 요소를 추가하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.users.insert([
  { _id: 1, name: "John Doe", hobbies: ["reading", "swimming"] },
  { _id: 2, name: "Jane Smith", hobbies: ["gardening", "cooking"] }
])
```

**쿼리 예제**

```
db.users.updateOne(
  { _id: 1 },
  { $push: { hobbies: "hiking" } }
)
```

**출력**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

업데이트를 실행한 후의 문서에 `hobbies` 배열`_id: 1`이 로 업데이트됩니다`[&quot;reading&quot;, &quot;swimming&quot;, &quot;hiking&quot;]`.

## 코드 예제
<a name="push-code"></a>

`$push` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.updateOne(
    { _id: 1 },
    { $push: { hobbies: "hiking" } }
  );

  console.log(result);
  client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    result = collection.update_one(
        {'_id': 1},
        {'$push': {'hobbies': 'hiking'}}
    )

    print(result.raw_result)
    client.close()

update_document()
```

------

# \$1rename
<a name="rename"></a>

Amazon DocumentDB의 `$rename` 연산자는 문서의 필드 이름을 바꾸는 데 사용됩니다. 이 연산자는 문서의 구조를 업데이트하거나 새 데이터 모델에 맞게 조정해야 할 때 특히 유용할 수 있습니다.

**파라미터**
+ `field`: 이름을 바꿀 필드입니다.
+ `newName`: 필드의 새 이름입니다.

## 예제(MongoDB 쉘)
<a name="rename-examples"></a>

다음 예제에서는 `$rename` 연산자를 사용하여 `&quot;Date.DoW&quot;` 필드가 로 설정된 문서에서 `&quot;DocName&quot;` 필드의 이름을 로 바꾸`&quot;Date.DayOfWeek&quot;`는 방법을 보여줍니다`&quot;Document 1&quot;`.

**샘플 문서 생성**

```
db.example.insertOne({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**쿼리 예제**

```
db.example.update(
    { "DocName": "Document 1" },
    { $rename: { "Date.DoW": "Date.DayOfWeek" } }
)
```

**출력**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DayOfWeek": "Saturday"
    },
    "Words": 2482
}
```

## 코드 예제
<a name="rename-code"></a>

`$rename` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
    const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
    const db = client.db('test');
    const collection = db.collection('example');

    await collection.updateOne(
        { "DocName": "Document 1" },
        { $rename: { "Date.DoW": "Date.DayOfWeek" } }
    );

    const updatedDoc = await collection.findOne({ "DocName": "Document 1" });
    console.log(updatedDoc);

    await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    collection.update_one(
        {"DocName": "Document 1"},
        {"$rename": {"Date.DoW": "Date.DayOfWeek"}}
    )

    updated_doc = collection.find_one({"DocName": "Document 1"})
    print(updated_doc)

    client.close()

example()
```

------

# \$1set
<a name="set-update"></a>

Amazon DocumentDB의 `$set` 연산자는 문서에서 지정된 필드의 값을 업데이트하는 데 사용됩니다. 이 연산자를 사용하면 문서 내에서 새 필드를 추가하거나 기존 필드를 수정할 수 있습니다. Amazon DocumentDB와 호환되는 MongoDB Java 드라이버의 기본 업데이트 연산자입니다.

**파라미터**
+ `field`: 업데이트할 필드입니다.
+ `value`: 필드의 새 값입니다.

## 예제(MongoDB 쉘)
<a name="set-examples"></a>

다음 예제에서는 `$set` 연산자를 사용하여 문서의 `Item` 필드를 업데이트하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.example.insert([
  {
    "Item": "Pen",
    "Colors": ["Red", "Green", "Blue", "Black"],
    "Inventory": {
      "OnHand": 244,
      "MinOnHand": 72
    }
  },
  {
    "Item": "Poster Paint",
    "Colors": ["Red", "Green", "Blue", "White"],
    "Inventory": {
      "OnHand": 120,
      "MinOnHand": 36
    }
  }
])
```

**쿼리 예제**

```
db.example.update(
  { "Item": "Pen" },
  { $set: { "Item": "Gel Pen" } }
)
```

**출력**

```
{
  "Item": "Gel Pen",
  "Colors": ["Red", "Green", "Blue", "Black"],
  "Inventory": {
    "OnHand": 244,
    "MinOnHand": 72
  }
}
```

## 코드 예제
<a name="set-code"></a>

`$set` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  await collection.updateOne(
    { "Item": "Pen" },
    { $set: { "Item": "Gel Pen" } }
  );

  const updatedDocument = await collection.findOne({ "Item": "Gel Pen" });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.example

    collection.update_one(
        {"Item": "Pen"},
        {"$set": {"Item": "Gel Pen"}}
    )

    updated_document = collection.find_one({"Item": "Gel Pen"})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1setOnInsert
<a name="setOnInsert"></a>

Amazon DocumentDB의 `$setOnInsert` 연산자는 문서가 삽입되는 경우 필드의 값을 설정하는 데 사용되지만 문서가 업데이트되는 경우에는 영향을 주지 않습니다.

**파라미터**
+ `field`: 설정할 필드입니다.
+ `value`: 필드에 할당할 값입니다.

## 예제(MongoDB 쉘)
<a name="setOnInsert-examples"></a>

다음 예제에서는 Amazon DocumentDB에서 `$setOnInsert` 연산자의 사용을 보여줍니다. 문서가 아직 없는 경우 새 문서를 생성하지만 문서가 업데이트되는 경우에는 영향을 미치지 않습니다.

**샘플 문서 생성**

```
db.users.insertOne({
  _id: 1,
  name: "John Doe",
  age: 30
})
```

**쿼리 예제 1 - 기존 문서 업데이트**

```
db.users.update(
  { _id: 1 },
  {
    $set: { age: 31 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**출력 1**

```
{
  _id: 1,
  name: "John Doe",
  age: 31
}
```

출력은 문서가 업데이트되었지만 문서가 이미 존재했기 때문에 `createdAt` 필드가 **추가되지** 않았음을 보여줍니다. 연`$setOnInsert`산자는 새 문서를 삽입할 때만 적용됩니다.

**쿼리 예제 2 - 새 문서 삽입(업서트)**

```
db.users.update(
  { _id: 2 },
  {
    $set: { name: "Jane Smith", age: 25 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**출력 2**

```
{
  _id: 2,
  name: "Jane Smith", 
  age: 25,
  createdAt: ISODate("2025-10-31T09:57:52.459Z")
}
}
```

## 코드 예제
<a name="setOnInsert-code"></a>

`$setOnInsert` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateWithSetOnInsert() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  await users.updateOne(
    { _id: 1 },
    {
      $set: { age: 31 },
      $setOnInsert: { createdAt: new Date() }
    },
    { upsert: true }
  );

  const updatedUser = await users.findOne({ _id: 1 });
  console.log(updatedUser);

  await client.close();
}

updateWithSetOnInsert();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_with_set_on_insert():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = users.update_one(
        {'_id': 1},
        {
            '$set': {'age': 31},
            '$setOnInsert': {'createdAt': datetime.datetime.now()}
        },
        upsert=True
    )

    updated_user = users.find_one({'_id': 1})
    print(updated_user)

    client.close()

update_with_set_on_insert()
```

------

# \$1slice
<a name="slice-update"></a>

`$slice` 업데이트 연산자는 크기를 제한하여 배열을 수정합니다. `$push` 연산자와 함께 사용하면 배열의 요소 수를 제한하여 지정된 수의 가장 최근 또는 가장 오래된 요소만 유지합니다.

**파라미터**
+ `field`: 수정할 배열 필드입니다.
+ `count`: 유지할 최대 요소 수입니다. 양수 값은 첫 번째 N 요소를 유지하고 음수 값은 마지막 N 요소를 유지합니다.

## 예제(MongoDB 쉘)
<a name="slice-update-examples"></a>

다음 예제에서는에서 `$slice` 업데이트 연산자를 사용하여 최근 점수의 고정 크기 배열을 `$push` 유지하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  scores: [85, 90, 78]
});
```

**쿼리 예제**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      scores: {
        $each: [92, 88],
        $slice: -3
      }
    }
  }
)
```

**출력**

```
{
  "_id" : 1,
  "name" : "Alice",
  "scores" : [ 78, 92, 88 ]
}
```

이 예제에서 `$slice: -3` 한정자는 배열에 새 값을 푸시한 후 마지막 세 요소만 유지합니다.

## 코드 예제
<a name="slice-update-code"></a>

`$slice` 업데이트 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        scores: {
          $each: [92, 88],
          $slice: -3
        }
      }
    }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.students

    collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'scores': {
                    '$each': [92, 88],
                    '$slice': -3
                }
            }
        }
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1sort
<a name="sort-update"></a>

`$sort` 업데이트 한정자는 `$push` 연산자와 함께 사용할 때 배열 요소를 정렬합니다. 지정된 필드 값 또는 요소 자체를 기준으로 배열 요소를 오름차순 또는 내림차순으로 정렬합니다.

**파라미터**
+ `field`: 수정할 배열 필드입니다.
+ `order`: 오`1`름차순 또는 내림차순에 `-1` 사용합니다.

## 예제(MongoDB 쉘)
<a name="sort-update-examples"></a>

다음 예제에서는 `$sort`에서 수정자를 사용하여 새 퀴즈 점수를 `$push` 추가하고 내림차순으로 정렬된 상태를 유지하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.students.insertOne({
  _id: 1,
  name: "Bob",
  quizzes: [
    { score: 85, date: "2024-01-15" },
    { score: 92, date: "2024-02-10" }
  ]
});
```

**쿼리 예제**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      quizzes: {
        $each: [{ score: 78, date: "2024-03-05" }],
        $sort: { score: -1 }
      }
    }
  }
)
```

**출력**

```
{
  "_id" : 1,
  "name" : "Bob",
  "quizzes" : [
    { "score" : 92, "date" : "2024-02-10" },
    { "score" : 85, "date" : "2024-01-15" },
    { "score" : 78, "date" : "2024-03-05" }
  ]
}
```

## 코드 예제
<a name="sort-update-code"></a>

`$sort` 업데이트 한정자를 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        quizzes: {
          $each: [{ score: 78, date: "2024-03-05" }],
          $sort: { score: -1 }
        }
      }
    }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.students

    collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'quizzes': {
                    '$each': [{'score': 78, 'date': '2024-03-05'}],
                    '$sort': {'score': -1}
                }
            }
        }
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1unset
<a name="unset-update"></a>

Amazon DocumentDB의 `$unset` 연산자는 문서에서 지정된 필드를 제거하는 데 사용됩니다. 를 사용하여 필드를 제거하면 문서에서 `$unset`필드가 삭제되고 그에 따라 문서 크기가 줄어듭니다. 이는 문서에서 불필요한 데이터를 제거하려는 경우에 유용할 수 있습니다.

**파라미터**
+ `field`: 문서에서 제거할 필드입니다. 이는 단일 필드이거나 중첩된 필드의 점선 경로일 수 있습니다.

## 예제(MongoDB 쉘)
<a name="unset-examples"></a>

다음 예제에서는 `$unset` 연산자를 사용하여 `example` 컬렉션의 문서에서 `Words` 필드를 제거하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.example.insert({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**쿼리 예제**

```
db.example.update(
    { "DocName" : "Document 1" },
    { $unset: { Words:1 } }
)
```

**출력**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    }
}
```

이 예제에서는 `$unset` 연산자를 사용하여 "문서 1"과 `DocName` 동일한 로 문서에서 `Words` 필드를 제거합니다. 결과 문서에는 더 이상 `Words` 필드가 포함되지 않습니다.

## 코드 예제
<a name="unset-code"></a>

`$unset` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function removeField() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  const result = await collection.updateOne(
    { "DocName": "Document 1" },
    { $unset: { "Words": 1 } }
  );

  console.log(`Modified ${result.modifiedCount} document(s)`);
  client.close();
}

removeField();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def remove_field():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    result = collection.update_one(
        {"DocName": "Document 1"},
        {"$unset": {"Words": 1}}
    )

    print(f"Modified {result.modified_count} document(s)")
    client.close()

remove_field()
```

------