빅데이터/nosql
mongodb JSON 데이터 upsert 하기(with 자바 라이브러리)
AndersonChoi
2021. 5. 25. 20:11
mongodb 자바 라이브러리 정의(in gradle)
dependencies {
implementation "org.mongodb:mongo-java-driver:3.4.1"
}
mongoClient 선언
MongoClient mongoClient = new MongoClient("localhost", 27027);
MongoCollection<Document> collection = database.getCollection(COLLECTION_NAME);
upsert 수행
String findKey = "{\"name\":\"wonyoung\"}"; // 찾아야할 데이터 값
int count = 1; // 추가하는 데이터
BasicDBObject keyObject = BasicDBObject.parse(findKey);
BasicDBObject countObject = new BasicDBObject("count", count);
BasicDBObject incrementDocument = new BasicDBObject("$inc", countObject); // increment를 수행할때는 반드시 $inc로 선언해야한다.
UpdateResult result = collection.updateOne(keyObject
, incrementDocument
, new UpdateOptions().upsert(true)); // 만약 "name":"wonyoung" 이 없다면 신규 도큐먼트를 생성한다
실행 결과
1. 데이터가 없는 경우
데이터가 존재하지 않으므로 새로 값이 insert 된다.
{
"name": "wonyoung",
"count": 1
}
UpdateOptions의 upsert() 에 true로 값을 주면 신규 도큐먼트를 생성한다.
public UpdateOptions upsert(boolean upsert)
Set to true if a new document should be inserted if there are no matches to the query filter.
2. 데이터가 있는 경우
아래와 같이 데이터가 있었다면
{
"name": "wonyoung",
"count": 9
}
count 값이 1 더 올라간다
{
"name": "wonyoung",
"count": 10
}
반응형