$position - Amazon DocumentDB

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

$position

Amazon DocumentDB의 $position 한정자는 $push 연산자가 요소를 삽입하는 배열의 위치를 지정합니다. $position 한정자가 없으면 $push 연산자가 배열 끝에 요소를 삽입합니다.

파라미터

  • field: 업데이트할 배열 필드입니다.

  • num: 제로 기반 인덱싱을 기반으로 요소를 삽입해야 하는 배열의 위치입니다.

참고: $position 한정자를 사용하려면 $each 한정자와 함께 표시되어야 합니다.

예제(MongoDB 쉘)

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

코드 예제

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