
MongoDBDriverWriteResult::getUpsertedCount 메서드는 업서트된 문서의 수를 반환합니다. 하지만 업서트된 문서의 ID를 얻을 수 있는 방법은 없습니다.
업서트된 문서의 ID를 얻으려면, MongoDB의 find 메서드를 사용하여 업서트된 문서를 찾을 수 있습니다.
예를 들어, 다음과 같이 코드를 작성할 수 있습니다.
#hostingforum.kr
java
MongoCollection collection = db.getCollection("컬렉션명");
Document document = new Document("키", "값");
WriteResult result = collection.insertOne(document);
long upsertedCount = result.getUpsertedCount();
// 업서트된 문서의 ID를 얻기 위해 find 메서드를 사용합니다.
FindIterable findIterable = collection.find(new Document("_id", result.getUpsertedId()));
for (Document document1 : findIterable) {
System.out.println(document1.get("_id"));
}
위의 코드에서 result.getUpsertedId() 메서드는 업서트된 문서의 ID를 반환합니다.
또한, MongoDB 4.2 버전 이상부터는 MongoDB의 find 메서드에 upsertedId 필드를 지정하여 업서트된 문서의 ID를 얻을 수 있습니다.
#hostingforum.kr
java
MongoCollection collection = db.getCollection("컬렉션명");
Document document = new Document("키", "값");
WriteResult result = collection.insertOne(document);
long upsertedCount = result.getUpsertedCount();
// 업서트된 문서의 ID를 얻기 위해 find 메서드를 사용합니다.
FindIterable findIterable = collection.find(new Document("_id", result.getUpsertedId()));
for (Document document1 : findIterable) {
System.out.println(document1.get("_id"));
}
위의 코드에서 upsertedId 필드를 지정하여 업서트된 문서의 ID를 얻을 수 있습니다.
또한, MongoDB의 aggregate 메서드를 사용하여 업서트된 문서의 ID를 얻을 수 있습니다.
#hostingforum.kr
java
MongoCollection collection = db.getCollection("컬렉션명");
Document document = new Document("키", "값");
WriteResult result = collection.insertOne(document);
long upsertedCount = result.getUpsertedCount();
// 업서트된 문서의 ID를 얻기 위해 aggregate 메서드를 사용합니다.
AggregationOptions options = AggregationOptions.builder().build();
AggregationPipeline pipeline = Aggregation.pipeline(
Aggregation.match(new Document("_id", result.getUpsertedId())),
Aggregation.project(new Document("_id", 1))
);
AggregationIterable aggregationIterable = collection.aggregate(pipeline, options);
for (Document document1 : aggregationIterable) {
System.out.println(document1.get("_id"));
}
위의 코드에서 aggregate 메서드를 사용하여 업서트된 문서의 ID를 얻을 수 있습니다.
따라서, MongoDBDriverWriteResult::getUpsertedCount 메서드는 업서트된 문서의 수를 반환합니다. 하지만 업서트된 문서의 ID를 얻으려면, MongoDB의 find 메서드, MongoDB 4.2 버전 이상부터의 find 메서드, MongoDB의 aggregate 메서드를 사용할 수 있습니다.
2025-03-14 11:02