MongoDB에서 컬렉션에 속한 여러 문서를 동시에 수정해야 할 때 가장 유용하게 쓰이는 메서드가 바로 updateMany()입니다. 이 메서드를 사용하면 필터 조건에 일치하는 모든 문서를 한 번의 작업으로 업데이트할 수 있습니다.
updateMany() 메서드의 기본 문법
db.COLLECTION_NAME.update(<filter>, <update>)
셸에서는 위와 같은 형태로 사용하며, Java에서는 com.mongodb.client.MongoCollection 인터페이스가 동일한 이름의 메서드를 제공합니다. 이 메서드에 필터(filter)와 업데이트 내용(update) 두 가지 인자를 전달하면, 조건에 맞는 여러 문서가 한꺼번에 수정됩니다.
전체 예제 코드
아래 예제는 샘플 문서 3개를 컬렉션에 삽입한 뒤, 도시(city)가 "Delhi"인 모든 문서를 "Vijayawada"로 변경하는 과정을 보여줍니다.
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
public class UpdatingMultipleDocuments {
public static void main( String args[] ) {
// Mongo 클라이언트 생성
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// 데이터베이스 연결
MongoDatabase database = mongo.getDatabase("myDatabase");
// 컬렉션 객체 가져오기
MongoCollection<Document> collection = database.getCollection("myCollection");
// 업데이트할 문서 준비
Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad");
Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Delhi");
Document document3 = new Document("name", "Rahim").append("age", 30).append("city", "Delhi");
// 생성한 문서들을 컬렉션에 삽입
List<Document> list = new ArrayList<Document>();
list.add(document1);
list.add(document2);
list.add(document3);
collection.insertMany(list);
// 삽입된 문서 목록 출력
System.out.println("List of the documents: ");
FindIterable<Document> iterDoc = collection.find();
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// 여러 문서 업데이트
Bson filter = new Document("city", "Delhi");
Bson newValue = new Document("city", "Vijayawada");
Bson updateOperationDocument = new Document("$set", newValue);
collection.updateMany(filter, updateOperationDocument);
System.out.println("Document update successfully...");
System.out.println("List of the documents after update");
iterDoc = collection.find();
it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}코드 핵심 포인트
- 필터(Filter):
new Document("city", "Delhi")— city 값이 "Delhi"인 문서만 대상으로 지정합니다. - 업데이트 연산자:
$set연산자를 감싸는 문서를 만들어 특정 필드만 변경하고 나머지 필드는 그대로 유지합니다. - updateMany() 호출: 조건에 일치하는 모든 문서가 한 번의 요청으로 갱신됩니다.
실행 결과
List of the documents:
Document{{_id=5e88a61fe7a0124a4fc51b2c, name=Ram, age=26, city=Hyderabad}}
Document{{_id=5e88a61fe7a0124a4fc51b2d, name=Robert, age=27, city=Delhi}}
Document{{_id=5e88a61fe7a0124a4fc51b2e, name=Rahim, age=30, city=Delhi}}
Document update successfully...
List of the documents after update
Document{{_id=5e88a61fe7a0124a4fc51b2c, name=Ram, age=26, city=Hyderabad}}
Document{{_id=5e88a61fe7a0124a4fc51b2d, name=Robert, age=27, city=Vijayawada}}
Document{{_id=5e88a61fe7a0124a4fc51b2e, name=Rahim, age=30, city=Vijayawada}}실행 결과를 보면 city가 "Delhi"였던 Robert와 Rahim의 문서만 "Vijayawada"로 변경되었고, 조건에 해당하지 않는 Ram의 문서는 그대로 유지된 것을 확인할 수 있습니다. 이처럼 updateMany()를 활용하면 반복문 없이도 대량의 문서를 효율적으로 갱신할 수 있습니다.