$pop - Amazon DocumentDB

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

$pop

Amazon DocumentDB의 $pop 연산자는 배열 필드에서 첫 번째 또는 마지막 요소를 제거하는 데 사용됩니다. 고정 크기 배열을 유지하거나 문서 내에서 대기열과 같은 데이터 구조를 구현해야 할 때 특히 유용합니다.

파라미터

  • field: 요소를 제거할 배열 필드의 이름입니다.

  • value: 제거할 요소의 위치를 결정하는 정수 값입니다. 값이 이면 마지막 요소가 1 제거되고 값이 이면 첫 번째 요소가 -1 제거됩니다.

예제(MongoDB 쉘)

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

코드 예제

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