$set - Amazon DocumentDB

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

$set

버전 8.0의 새로운 기능

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

Amazon DocumentDB의 $set 집계 단계를 사용하면 집계 파이프라인 중에 설명서의 새 필드를 추가하거나 기존 필드 값을 업데이트할 수 있습니다.

파라미터

  • expression: 평가할 표현식입니다. 필드 참조 및 산술 연산을 포함하여 유효한 집계 표현식일 수 있습니다.

예제(MongoDB 쉘)

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

코드 예제

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