개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.06.27 05:59

MongoDBDriverBulkWrite::count 오류 해결 방법을 알려주세요.

목록
  • 마이크로서비스연구가 23일 전 2025.06.27 05:59 인기
  • 191
    1
저는 MongoDBDriverBulkWrite::count를 사용하여 BulkWrite 작업의 카운트 값을 가져오려고 합니다.
하지만 BulkWrite 작업이 성공적으로 완료된 후에도 count 값이 0이 반환되는 오류가 발생하고 있습니다.
이러한 문제가 발생하는 원인은 무엇이며, 해결 방법을 알려주세요.

다음은 제가 사용하는 코드입니다.

java

MongoCollection collection = db.getCollection("mycollection");

BulkWriteOptions options = new BulkWriteOptions();

options.setOrdered(false);

List> writes = new ArrayList<>();

writes.add(new UpdateOneModel<>(Filters.eq("id", 1), new Document("$set", new Document("name", "John"))));

BulkWriteResult result = collection.bulkWrite(writes, options);

long count = result.getModifiedCount();



count 값이 0이 반환되는 오류가 발생하는 이유와 해결 방법을 알려주세요.

    댓글목록

    profile_image
    나우호스팅  23일 전



    MongoDBDriverBulkWrite::count 오류는 BulkWrite 작업의 카운트 값을 가져올 때 발생하는 오류입니다.

    이러한 문제가 발생하는 원인은 BulkWrite 작업의 결과에 포함되지 않은 수정된 문서의 수를 가져오려고 할 때 발생합니다.

    해결 방법은 BulkWrite 작업의 결과에 포함되지 않은 수정된 문서의 수를 가져오려고 할 때, getModifiedCount() 대신 getUpsertedCount() 또는 getInsertedCount() 메서드를 사용하는 것입니다.

    또한, BulkWrite 작업의 결과에 포함되지 않은 수정된 문서의 수를 가져오려고 할 때, getModifiedCount() 메서드를 사용하는 대신, MongoDB의 aggregation framework를 사용하는 방법도 있습니다.

    아래는 aggregation framework를 사용하는 방법의 예제입니다.

    #hostingforum.kr
    java
    
    List> writes = new ArrayList<>();
    
    writes.add(new UpdateOneModel<>(Filters.eq("id", 1), new Document("$set", new Document("name", "John"))));
    
    
    
    BulkWriteResult result = collection.bulkWrite(writes, options);
    
    
    
    List pipeline = new ArrayList<>();
    
    pipeline.add(new Document("$match", new Document("modifiedCount", new Document("$gt", 0))));
    
    pipeline.add(new Document("$group", new Document("_id", null).append("count", new Document("$sum", "$modifiedCount"))));
    
    
    
    List resultDocs = collection.aggregate(pipeline).into(new ArrayList<>());
    
    long count = resultDocs.get(0).getLong("count");
    
    


    이러한 방법을 사용하면 BulkWrite 작업의 결과에 포함되지 않은 수정된 문서의 수를 정확하게 가져올 수 있습니다.

    2025-06-27 06:00

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 37,633건 / 59 페이지

검색

게시물 검색