$slice - Amazon DocumentDB

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

$slice

$slice 프로젝션 연산자는 쿼리 결과에 반환되는 배열 요소의 수를 제한합니다. 이를 통해 전체 배열을 로드하지 않고도 배열 필드의 시작 또는 끝에서 특정 수의 요소를 검색할 수 있습니다.

파라미터

  • field: 프로젝션할 배열 필드입니다.

  • count: 반환할 요소 수입니다. 양수 값은 시작에서 요소를 반환하고, 음수 값은 끝에서 반환합니다.

예제(MongoDB 쉘)

다음 예제에서는 $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" ] }

코드 예제

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