문서 메뉴
문서 홈
/ / /
Java 동기화 드라이버
/ / /

문서의 배열 업데이트

이 페이지의 내용

  • 개요
  • 샘플 문서
  • 업데이트 지정
  • 배열 요소 지정
  • 첫 번째 일치하는 배열 요소
  • 모든 배열 요소 일치
  • 여러 배열 요소 일치하기

이번 가이드에서는 MongoDB Java 드라이버로 문서에서 배열을 업데이트하는 방법을 알아봅니다.

배열을 업데이트하려면 다음을 수행해야 합니다.

  • 수행할 업데이트 지정

  • 업데이트를 적용할 배열 요소 지정

  • 다음 사양을 사용하여 업데이트 작업 수행

다음 섹션에서는 이 샘플 문서를 업데이트하는 예를 제공합니다.

{ "_id": 1, "color": "green", "qty": [8, 12, 18] }

이 페이지의 예제에서는 MongoCollection 클래스의 findOneAndUpdate() 메서드를 사용하여 문서를 검색하고 업데이트합니다. 각 예제에서는 FindOneAndUpdateOptions 클래스의 인스턴스를 사용하여 업데이트가 발생한 후 MongoDB가 문서를 검색하도록 합니다. findOneAndUpdate() 메서드에 대한 자세한 내용은 복합 연산 가이드를 참조하세요.

업데이트를 지정하려면 Updates 빌더를 사용합니다. Updates 빌더는 업데이트 사양을 구성하기 위한 정적 유틸리티 메서드를 제공합니다. 배열과 함께 Updates 빌더를 사용하는 방법에 대한 자세한 내용은 업데이트 빌더 가이드를 참조하세요.

다음 예제에서는 이러한 작업을 수행합니다.

  • 샘플 문서에 대한 쿼리

  • 쿼리 필터와 일치하는 문서의 qty 배열에 '17'을 추가

Bson filter = Filters.eq("_id", 1);
Bson update = Updates.push("qty", 17);
// Defines options that configure the operation to return a document in its post-operation state
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
.returnDocument(ReturnDocument.AFTER);
// Updates the first document that matches the filter and prints the updated document as JSON
Document result = collection.findOneAndUpdate(filter, update, options);
System.out.println(result.toJson());

앞의 예에서는 원본 문서를 다음 상태로 업데이트합니다:

{ "_id": 1, "color": "green", "qty": [8, 12, 18, 17] }

업데이트할 배열 요소를 지정하려면 위치 연산자를 사용합니다. 위치 연산자는 업데이트할 첫 번째, 전체 또는 특정 배열 요소를 지정할 수 있습니다.

위치 연산자를 사용하여 배열의 요소를 지정하려면 점 표기법을 사용합니다. 점 표기법은 BSON 객체를 탐색하기 위한 속성 액세스 구문입니다.

자세한 내용은 점 표기법에 대한 MongoDB Server 수동 항목을 참조하세요.

쿼리 필터와 일치하는 첫 번째 배열 요소를 업데이트하려면 위치 $ 연산자를 사용합니다. 위치 $ 연산자를 사용하려면 배열 필드가 쿼리 필터의 일부로 나타나야 합니다.

다음 예제에서는 이러한 작업을 수행합니다.

  • 값 '18'을 포함하는 qty 필드가 있는 문서를 쿼리

  • 쿼리 필터와 일치하는 문서의 첫 번째 배열 값을 '3'만큼 감소

Bson filter = Filters.eq("qty", 18);
Bson update = Updates.inc("qty.$", -3);
// Defines options that configure the operation to return a document in its post-operation state
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
.returnDocument(ReturnDocument.AFTER);
// Updates the first document that matches the filter and prints the updated document as JSON
Document result = collection.findOneAndUpdate(filter, update, options);
System.out.println(result.toJson());

앞의 예에서는 원본 문서를 다음 상태로 업데이트합니다:

{ "_id": 1, "color": "green", "qty": [8, 12, 15] }

이 섹션에 언급된 메서드 및 연산자에 대한 자세한 내용은 다음 리소스를 참조하세요.

배열의 모든 요소를 업데이트하려면 모든 위치 $[] 연산자를 사용합니다.

다음 예제에서는 이러한 작업을 수행합니다.

  • 샘플 문서에 대한 쿼리

  • 쿼리 필터와 일치하는 배열 요소에 '2'를 곱함

Bson filter = Filters.eq("_id", 1);
Bson update = Updates.mul("qty.$[]", 2);
// Defines options that configure the operation to return a document in its post-operation state
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
.returnDocument(ReturnDocument.AFTER);
// Updates the first document that matches the filter and prints the updated document as JSON
Document result = collection.findOneAndUpdate(filter, update, options);
System.out.println(result.toJson());

앞의 예에서는 원본 문서를 다음 상태로 업데이트합니다:

{ "_id": 1, "color": "green", "qty": [16, 24, 36] }

이 섹션에 언급된 메서드 및 연산자에 대한 자세한 내용은 다음 리소스를 참조하세요.

필터와 일치하는 배열 요소를 업데이트하려면 필터링된 위치 $[<identifier>] 연산자를 사용하세요. 업데이트할 배열 요소를 지정하려면 업데이트 작업에 배열 필터를 포함해야 합니다.

<identifier>은(는) 배열 필터에 지정하는 이름입니다. 이 값은 소문자로 시작해야 하며 영숫자만 포함할 수 있습니다.

다음 예제에서는 이러한 작업을 수행합니다.

  • 샘플 문서에 대한 쿼리

  • '15'보다 작은 값을 검색하도록 배열 필터를 설정합니다.

  • 쿼리 필터와 일치하는 배열 요소를 '5'만큼 증가시킵니다.

Bson filter = Filters.eq("_id", 1);
Bson smallerFilter = Filters.lt("smaller", 15);
// Defines options that configure the document's return state and apply the array value filter
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
.returnDocument(ReturnDocument.AFTER)
.arrayFilters(Arrays.asList(smallerFilter));
// Creates an update document to increase the matched array values by "5"
Bson update = Updates.inc("qty.$[smaller]", 5);
// Updates the first document that matches the filter and prints the updated document as JSON
Document result = collection.findOneAndUpdate(filter, update, options);
System.out.println(result.toJson());

앞의 예에서는 원본 문서를 다음 상태로 업데이트합니다:

{ "_id": 1, "color": "green", "qty": [13, 17, 18] }

이 섹션에 언급된 메서드 및 연산자에 대한 자세한 내용은 다음 리소스를 참조하세요.

돌아가기

문서 수정

다음

한 번의 작업으로 삽입 또는 업데이트