문서 업데이트
이 페이지의 내용
개요
이 가이드 에서는 MongoDB 컬렉션 에서 문서를 업데이트 방법을 학습 수 있습니다. 업데이트 작업은 하나 이상의 문서에서 변경할 필드와 값을 지정합니다. 업데이트 문서 에 지정된 변경 사항을 쿼리 필터하다 와 일치하는 하나 이상의 문서에 적용 .
내장된 배열을 업데이트하거나 한 번의 작업으로 업데이트 또는 삽입하는 방법을 학습 다음 페이지를 참조하세요.
업데이트 작업은 필드와 값을 수정할 수 있습니다.
updateOne() 메서드는 쿼리 필터하다 일치하는 첫 번째 문서 변경하고
updateMany() 메서드는 쿼리 필터하다 와 일치하는 모든 문서를 변경합니다.
다음과 같이 MongoCollection
인스턴스에서 updateOne()
및 updateMany()
메서드를 호출할 수 있습니다.
collection.updateOne(<query>, <updateDocument>); collection.updateMany(<query>, <updateDocument>);
작업 매개변수 업데이트
updateOne()
및 updateMany()
메서드에는 모두 다음과 같은 매개 변수가 있습니다.
query
는 컬렉션에서 업데이트할 문서와 일치하는 조건으로 쿼리 필터를 지정합니다.update
는 일치하는 문서에서 수정할 필드 및 값을 지정합니다. 이 섹션의 예시에서는 업데이트 빌더를 사용하여 업데이트 문서를 생성합니다.(선택 사항)
updateOptions
는 드라이버가 업데이트 작업을 수행하는 방식을 사용자 지정할 수 있는 옵션을 지정합니다. 이 유형에 대해 자세히 알아보려면 UpdateOptions에 대한 API 문서를 참조하세요.
다음과 같이 Updates
빌더를 사용하여 updateDocument
를 만들 수 있습니다.
Bson update = Updates.operator(<field>, <value>);
업데이트 빌더 의 전체 목록과 사용법을 보려면 API 문서에서 업데이트를 참조하세요.
예시
다음 예에서는 페인트 가게에서 5가지 색상의 페인트를 판매합니다. paint_inventory
컬렉션은 현재 인벤토리를 나타냅니다.
{ "_id": 1, "color": "red", "qty": 5 } { "_id": 2, "color": "purple", "qty": 8 } { "_id": 3, "color": "yellow", "qty": 0 } { "_id": 4, "color": "green", "qty": 6 } { "_id": 5, "color": "pink", "qty": 0 }
하나의 예제 업데이트
다음 예시는 qty
값이 0
인 첫 번째 일치 문서에서 color
필드 값을 변경하는 방법을 보여줍니다.
Bson filter = Filters.eq("qty", 0); Bson update = Updates.set("color", "dandelion"); // Updates first matching document UpdateResult result = collection.updateOne(filter, update);
여러 문서가 updateOne()
메서드에 지정된 쿼리 필터하다 와 일치하는 경우 첫 번째 결과를 업데이트합니다. 다음 코드와 같이 UpdateOptions
인스턴스 에서 정렬을 지정하여 서버 업데이트 작업을 수행하기 전에 일치하는 문서에 순서를 적용 할 수 있습니다.
UpdateOptions options = UpdateOptions.sort(ascending("color")); UpdateResult result = collection.updateOne(filter, document, options);
다수 업데이트 예시
페인트 매장은 새 배송을 받아 재고를 업데이트해야 합니다. 배송에는 각 페인트 색상의 캔이 20 개 포함되어 있습니다.
인벤토리를 업데이트하려면 다음을 지정하여 updateMany()
메서드를 호출합니다.
모든 색상과 일치하는 쿼리 필터하다
qty
필드20
만큼 증가시키는 지침이 포함된 문서 업데이트합니다.
Bson filter = Filters.empty(); Bson update = Updates.inc("qty", 20); // Updates all documents and prints the number of matched and modified documents UpdateResult result = collection.updateMany(filter, update); System.out.println("Matched document count: " + result.getMatchedCount()); System.out.println("Modified document count: " + result.getModifiedCount());
앞의 코드의 출력은 다음과 유사합니다.
Matched document count: 5 Modified document count: 5
다음은 paint_inventory
컬렉션에서 업데이트된 문서를 보여줍니다.
{ "_id": 1, "color": "red", "qty": 25 } { "_id": 2, "color": "purple", "qty": 28 } { "_id": 3, "color": "yellow", "qty": 20 } { "_id": 4, "color": "green", "qty": 26 } { "_id": 5, "color": "pink", "qty": 20 }
업데이트 작업의 쿼리 필터와 일치하는 문서가 0개이면 updateMany()
은 컬렉션의 문서를 변경하지 않습니다. 일치하는 문서가 없는 경우 업데이트하는 대신 새 문서를 삽입하는 방법을 알아보려면 업서트 가이드 를 참조하세요.
중요
updateOne()
및 updateMany()
메서드는 컬렉션의 고유 인덱스 제약 조건을 위반하는 문서를 변경할 수 없습니다. 고유 인덱스의 제약 조건에 대한 자세한 내용은 MongoDB Server 매뉴얼의 고유 인덱스를 참조하세요.
업데이트 예시: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습 MongoClient 만들기 가이드 를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된
sample_mflix
데이터베이스의 movies
컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas의 무료 계층에서 데이터베이스에 로드할 수 있습니다.
다음 코드는 1개의 업데이트 작업과 다수의 업데이트 작업을 수행하는 완전한 독립형 파일 입니다.
// Updates the first document that matches a query filter by using the Java driver package org.example; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.Updates; import com.mongodb.client.result.UpdateResult; import static com.mongodb.client.model.Filters.gt; public class Update { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); // Instructs the driver to insert a new document if none match the query UpdateOptions options = new UpdateOptions().upsert(true); Document updateOneQuery = new Document().append("title", "Cool Runnings 2"); // Creates instructions to update the values of three document fields Bson updateOneUpdates = Updates.combine( Updates.set("runtime", 99), Updates.addToSet("genres", "Sports"), Updates.currentTimestamp("lastUpdated")); // Updates the first document that has a "title" value of "Cool Runnings 2" UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options); // Prints the number of updated documents and the upserted document ID, if an upsert was performed System.out.println("Number of documents updated - update one: " + result.getModifiedCount()); System.out.println("Upserted document ID: " + result.getUpsertedId()); Bson updateManyQuery = gt("num_mflix_comments", 50); // Creates instructions to update the values of two document fields Bson updateManyUpdates = Updates.combine( Updates.addToSet("genres", "Frequently Discussed"), Updates.currentTimestamp("lastUpdated")); // Updates documents that have a "num_mflix_comments" value over 50 UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates); // Prints the number of updated documents System.out.println("\nNumber of documents updated - update many: " + result.getModifiedCount()); } } }
updateOne() modified document count: 1 Upserted ID: null updateMany() modified document count: 242
바꾸기
대체 작업은 collection에서 하나의 문서를 대체합니다. 대체는 쿼리 필터가 일치하는 문서와 대체 문서 간에 발생합니다.
replaceOne() 메서드는 일치하는 문서의 모든 기존 필드와 값(_id
필드 제외)을 제거하고 대체 문서로 대체합니다.
다음과 같이 MongoCollection
인스턴스에서 replaceOne()
메서드를 호출할 수 있습니다.
collection.replaceOne(<query>, <replacement>);
작업 매개변수 바꾸기
replaceOne()
메서드에는 다음과 같은 매개변수가 있습니다.
query
는 컬렉션에서 교체할 문서와 일치하는 조건으로 쿼리 필터를 지정합니다.replacement
은 일치하는 문서 대체할 새Document
객체 의 필드와 값을 지정합니다.(선택 사항)
replaceOptions
는 드라이버가 교체 작업을 수행하는 방법을 사용자 지정하기 위해 설정할 수 있는 옵션을 지정합니다. 이 유형에 대한 자세한 내용은 ReplaceOptions에 대한 API 문서를 참조하세요.
하나의 예제 바꾸기
페인트 저장 은 재고를 다시 업데이트 해야 함을 인식합니다. 분홍 페인트가 20 캔이라고 생각했던 것이 실제로는 주황색 페인트 캔이 25 캔이었습니다.
인벤토리를 업데이트하려면 다음을 지정하여 replaceOne()
메서드를 호출합니다.
color
가 '분홍색'인 문서와 일치하는 쿼리 필터color
이 '주황색'이고qty
이 '25'인 대체 문서입니다.
Bson filter = Filters.eq("color", "pink"); Document document = new Document("color", "orange").append("qty", 25); // Replaces the first document that matches the filter with a new document UpdateResult result = collection.replaceOne(filter, document); // Prints the number of matched and modified documents System.out.println("Matched document count: " + result.getMatchedCount()); System.out.println("Modified document count: " + result.getModifiedCount());
앞의 코드의 출력은 다음과 유사합니다.
Matched document count: 1 Modified document count: 1
다음은 업데이트된 문서를 보여줍니다.
{ "_id": 5, "color": "orange", "qty": 25 }
여러 문서가 replaceOne()
메서드에 지정된 쿼리 필터하다 와 일치하는 경우 첫 번째 결과를 대체합니다. 다음 코드와 같이 ReplaceOptions
인스턴스 에서 정렬을 지정하여 서버 바꾸기 작업을 수행하기 전에 일치하는 문서에 순서를 적용 할 수 있습니다.
ReplaceOptions options = ReplaceOptions.sort(ascending("qty")); UpdateResult result = collection.replaceOne(filter, document, options);
바꾸기 작업의 쿼리 필터와 일치하는 문서가 0개이면 replaceOne()
은 컬렉션의 문서를 변경하지 않습니다. 일치하는 문서가 없는 경우 새 문서를 삽입하는 대신 업서트 가이드 를 참조하세요.
중요
replaceOne()
메서드는 컬렉션의 고유 인덱스 제약 조건을 위반하는 문서를 변경할 수 없습니다. 고유 인덱스에 대한 제약 조건에 대한 자세한 내용은 MongoDB Server 매뉴얼의 고유 인덱스 를 참조하세요.
하나의 예제 바꾸기: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습 MongoClient 만들기 가이드 를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된
sample_mflix
데이터베이스의 movies
컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas의 무료 계층에서 데이터베이스에 로드할 수 있습니다.
다음 코드는 하나의 교체 작업을 수행하는 완전한 독립형 파일 입니다.
// Replaces the first document that matches a filter by using the Java driver package org.example; import static com.mongodb.client.model.Filters.eq; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.ReplaceOptions; import com.mongodb.client.result.UpdateResult; public class ReplaceOne { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); Bson query = eq("title", "Music of the Heart"); // Creates a new document containing "title" and "fullplot" fields Document replaceDocument = new Document(). append("title", "50 Violins"). append("fullplot", " A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music"); // Instructs the driver to insert a new document if none match the query ReplaceOptions opts = new ReplaceOptions().upsert(true); // Replaces the first document that matches the filter with a new document UpdateResult result = collection.replaceOne(query, replaceDocument, opts); // Prints the number of modified documents and the upserted document ID, if an upsert was performed System.out.println("Modified document count: " + result.getModifiedCount()); System.out.println("Upserted id: " + result.getUpsertedId()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { System.err.println("Unable to replace due to an error: " + me); } } }
Modified document count: 0 Upserted id: BsonObjectId{ ... }
추가 정보
API 문서
이 페이지에 사용된 메서드 및 클래스에 대한 자세한 내용은 다음 API 설명서를 참조하세요.