기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$addToSet
$addToSet 집계 연산자는 각 그룹에 대해 지정된 표현식에서 고유한 값의 배열을 반환합니다. $group 스테이지 내에서 고유한 값을 누적하여 중복을 자동으로 제거하는 데 사용됩니다.
파라미터
예제(MongoDB 쉘)
다음 예제에서는 $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' ] }
]
창 연산자 사용 예제(MongoDB Shell)
버전 8.0.2에서 새로 추가되었습니다.
연$addToSet산자는 $setWindowFields 스테이지에서 창 연산자로 사용할 수도 있습니다. 이 컨텍스트에서는 각 창의 문서에 대해 지정된 표현식의 고유 값 배열을 반환합니다. output 필드 아래에 연산자를 지정하고 선택적으로 window 문서로 창 경계를 정의합니다.
에서 창 연산자로 사용할 경우 $setWindowFields$addToSet는 100MB의 중간 데이터로 제한됩니다. 이 제한을 초과하는 작업은 오류를 반환합니다.
샘플 문서 생성
db.visits.insertMany([
{ _id: 1, customer: "Alice", day: 1, city: "Seattle" },
{ _id: 2, customer: "Alice", day: 2, city: "Portland" },
{ _id: 3, customer: "Alice", day: 3, city: "Seattle" },
{ _id: 4, customer: "Bob", day: 1, city: "Boston" },
{ _id: 5, customer: "Bob", day: 2, city: "Boston" }
]);
쿼리 예제
다음 예제에서는 문서를 기준으로 분할하고customer, 각 파티션을 기준으로 정렬하고day, 파티션 시작부터 현재 문서까지 고유한 city 값 집합을 반환합니다.
db.visits.aggregate([
{
$setWindowFields: {
partitionBy: "$customer",
sortBy: { day: 1 },
output: {
citiesSoFar: {
$addToSet: "$city",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
출력
[
{ "_id": 1, "customer": "Alice", "day": 1, "city": "Seattle", "citiesSoFar": [ "Seattle" ] },
{ "_id": 2, "customer": "Alice", "day": 2, "city": "Portland", "citiesSoFar": [ "Portland", "Seattle" ] },
{ "_id": 3, "customer": "Alice", "day": 3, "city": "Seattle", "citiesSoFar": [ "Portland", "Seattle" ] },
{ "_id": 4, "customer": "Bob", "day": 1, "city": "Boston", "citiesSoFar": [ "Boston" ] },
{ "_id": 5, "customer": "Bob", "day": 2, "city": "Boston", "citiesSoFar": [ "Boston" ] }
]
각 문서는 시작부터 현재 문서까지 파티션 내의 고유 city 값 집합citiesSoFar인 로 보강됩니다. 누적기 양식과 마찬가지로 반환된 배열의 값 순서는 보장되지 않습니다.
코드 예제
$addToSet 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누산기 사용량()과 창 연산자 사용량($group)을 모두 보여줍니다. $setWindowFields
- 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');
// Accumulator usage: collect unique values per group
const orders = db.collection('orders');
await 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 }
]);
const accumulatorResult = await orders.aggregate([
{
$group: {
_id: "$customer",
cities: { $addToSet: "$city" }
}
}
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Window operator usage: running set of unique values within each partition
const visits = db.collection('visits');
await visits.insertMany([
{ _id: 1, customer: "Alice", day: 1, city: "Seattle" },
{ _id: 2, customer: "Alice", day: 2, city: "Portland" },
{ _id: 3, customer: "Alice", day: 3, city: "Seattle" },
{ _id: 4, customer: "Bob", day: 1, city: "Boston" },
{ _id: 5, customer: "Bob", day: 2, city: "Boston" }
]);
const windowResult = await visits.aggregate([
{
$setWindowFields: {
partitionBy: "$customer",
sortBy: { day: 1 },
output: {
citiesSoFar: {
$addToSet: "$city",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
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']
# Accumulator usage: collect unique values per group
orders = db['orders']
orders.insert_many([
{ '_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 }
])
accumulator_result = list(orders.aggregate([
{
'$group': {
'_id': '$customer',
'cities': { '$addToSet': '$city' }
}
}
]))
print('Accumulator result:', accumulator_result)
# Window operator usage: running set of unique values within each partition
visits = db['visits']
visits.insert_many([
{ '_id': 1, 'customer': 'Alice', 'day': 1, 'city': 'Seattle' },
{ '_id': 2, 'customer': 'Alice', 'day': 2, 'city': 'Portland' },
{ '_id': 3, 'customer': 'Alice', 'day': 3, 'city': 'Seattle' },
{ '_id': 4, 'customer': 'Bob', 'day': 1, 'city': 'Boston' },
{ '_id': 5, 'customer': 'Bob', 'day': 2, 'city': 'Boston' }
])
window_result = list(visits.aggregate([
{
'$setWindowFields': {
'partitionBy': '$customer',
'sortBy': { 'day': 1 },
'output': {
'citiesSoFar': {
'$addToSet': '$city',
'window': { 'documents': ['unbounded', 'current'] }
}
}
}
}
]))
print('Window result:', window_result)
client.close()
example()