본문으로 바로가기

mongo 2.0 버전에서 document를 upcert하는 save라는 편리한 기능이 있었지만

MongoClient로 변경되면서 save기능이 없어졌다.

 

현재는 updateOne과 replaceOne이 save 기능을 대체하고 있는데 

 

두메서드는 차이가 있다.

 

updateOne은.

result = collection.updateOne(where, update, updateOptions);

위처럼 where 값과 값이 존재할경우 update할 document를 입력하면 된다.

 

replaceOne은

ObjectId objId= (ObjectId)obj.get("_id");
collection.replaceOne(new BasicDBObject("_id",objId), obj, option);

위처럼 사용할 수 있다.

 

그런데 두 메서드에는 차이가 있다.

updateOne 도큐먼트의 필드를 변경하는 것이고 replaceOne은 document 전체를 변경한다는 의미이다.

 

그러므로 updateOne에는 update 영역에 $set을 넣고 도큐먼트를 감싸야 한다.

replaceOne은 document만 넣어도 대체 가능하다.

 

replaceOne시

ObjectId objId= (ObjectId)obj.get("_id");

UpdateOptions option = new UpdateOptions();
option.upsert(true);

UpdateResult updateResult = collection.replaceOne(new BasicDBObject("_id",objId), obj, option);

위처럼 upsert를 true로 넘긴다면 기존 save처럼 존재하지 않다면 insert가 된다.