정의
$addToSetThe
$addToSetoperator adds a value to an array unless the value is already present, in which case$addToSetdoes nothing to that array.
참고
명확화
이 페이지에서는 $addToSet을 업데이트 연산자로 사용할 때의 사용 방법을 설명합니다.
$addToSet를 다른 다음 문맥에서도 사용할 수 있습니다:
$addToSet (accumulator), 가변적인 입력 문서 수에 기초하여 단일 집계된 값을 반환합니다.$addToSet (window function)는 특정 창의 문서에서 고유한 값의 배열을 반환하기 위해$setWindowFields단계에서 사용됩니다.
호환성
다음 환경에서 호스팅되는 배포에 $addToSet 사용할 수 있습니다.
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: MongoDB의 구독 기반 자체 관리 버전
MongoDB Community: MongoDB의 소스 사용 가능 무료 자체 관리 버전
구문
The $addToSet operator has the form:
{ $addToSet: { <field1>: <value1>, ... } }
내장된 문서나 배열에 <field> 기호를 지정하려면 점 표기법을사용하십시오.
행동
MongoDB 5.0부터 업데이트 연산자는 문자열 기반 이름이 있는 문서 필드를 사전순으로 처리합니다. 숫자 이름이 있는 필드는 숫자 순서대로 처리됩니다. 자세한 내용은 업데이트 운영자 동작을 참조하십시오.
$addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set.
Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $addToSet with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).
누락된 필드
If you use $addToSet on a field that is absent from the document to update, $addToSet creates the array field with the specified value as its element.
필드는 배열이 아닙니다.
If you use $addToSet on a field that is not an array, the operation fails.
예를 들어 pigments 컬렉션을 만듭니다.
db.pigments.insertOne( { _id: 1, colors: "blue, green, red" } )
The colors field is not an array. The following $addToSet operation fails:
db.pigments.updateOne( { _id: 1 }, { $addToSet: { colors: "mauve" } } )
추가할 값은 배열입니다.
If the value is an array, $addToSet appends the whole array as a single element.
alphabet 컬렉션을 생성합니다.
db.alphabet.insertOne( { _id: 1, letters: ["a", "b"] } )
다음 작업은 letters 필드에 배열 [ "c", "d" ]을 추가합니다.
db.alphabet.updateOne( { _id: 1 }, { $addToSet: { letters: [ "c", "d" ] } } )
배열 [ "c", "d" ]이 단일 요소로 추가됩니다.
{ _id: 1, letters: [ 'a', 'b', [ 'c', 'd' ] ] }
팁
To add each element of the value separately, use the $each modifier with $addToSet. See $each Modifier for details.
문서로 값을 추가하기
값이 문서인 경우, 배열의 기존 문서가 추가할 문서와 정확히 일치하면 MongoDB는 해당 문서가 중복된 것으로 판단합니다. 즉, 기존 문서에는 정확히 동일한 필드와 값이 있으며 필드의 순서도 동일합니다. 필드 순서가 중요하며, MongoDB가 문서가 기존 배열 요소의 중복인지 판단하기 위해 문서의 일부 필드만 비교하도록 지정할 수 없습니다.
예시
inventory 컬렉션을 생성합니다.
db.inventory.insertOne( { _id: 1, item: "polarizing_filter", tags: [ "electronics", "camera" ] } )
배열에 추가
다음 작업은 "accessories" 배열에 존재하지 않으므로 "accessories" 요소를 tags 배열에 추가합니다.
db.inventory.updateOne( { _id: 1 }, { $addToSet: { tags: "accessories" } } )
이미 존재하는 값
The following $addToSet operation has no effect because "camera" is already an element of the tags array:
db.inventory.updateOne( { _id: 1 }, { $addToSet: { tags: "camera" } } )
$each Modifier
You can use the $addToSet operator with the $each modifier. The $each modifier allows the $addToSet operator to add multiple values to the array field.
컬렉션 inventory에는 다음 문서가 있습니다.
db.inventory.insertOne ( { _id: 2, item: "cable", tags: [ "electronics", "supplies" ] } )
Then the following operation uses the $addToSet operator with the $each modifier to add multiple elements to the tags array:
db.inventory.updateOne( { _id: 2 }, { $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } } )
이 작업은 tags 배열에 "camera" 및 "accessories"만 추가합니다. "electronics" 이 이미 배열에 있었습니다:
{ _id: 2, item: "cable", tags: [ "electronics", "supplies", "camera", "accessories" ] }