본문 바로가기

History

java-mongo-driver CRUD 예제

다건의 오브젝트 찾기
 
List toolList = new ArrayList();
DBCollection coll = db.getCollection("tool_object");
 
/* cate_open:"category", ext_open:"true" 인 오브젝트를 찾음 */
BasicDBObject query = new BasicDBObject("cate_open", category).append("ext_open", "true");
cursor = coll.find(query);
 
/* "use" 속성값으로 정렬 */
cursor.sort(new BasicDBObject("use", -1));
while(cursor.hasNext()) {
toolList.add(cursor.next());
}
return toolList;

또는
  
List toolList = new ArrayList();
DBCollection coll = mongo.getCollection("tool_object");
 
/* team.id 속성의 값이 teamCode 인 오브젝트를 찾음 */
BasicDBObject query = new BasicDBObject();
query.put("team.id", teamCode);
 
DBCursor cursor = coll.find(query);
cursor.sort(new BasicDBObject("team", -1));

오브젝트 삽입
  
DBCollection coll = mongo.getCollection("tool_object");
BasicDBObject doc =
    new BasicDBObject("name", toolInfo.get("name")).
append("tUrl", toolInfo.get("t_url")).
append("iUrl", toolInfo.get("t_ico")).
    append("desc", toolInfo.get("t_desc")).
    append("guide", toolInfo.get("t_guide")).
    append("team", new BasicDBObject("id", toolInfo.get("team_id")).append("name", toolInfo.get("team_name"))).
    append("assistor", new BasicDBObject("id", toolInfo.get("u_id")).append("name", toolInfo.get("u_name"))).
    append("team_open", toolInfo.get("team_open")).
    append("cate_team", toolInfo.get("cate_team")).
    append("ext_open", toolInfo.get("ext_open")).
    append("cate_open", toolInfo.get("cate_open")).
    append("use", new BasicDBObject("day", 0).append("month", 0).append("year", 0));
coll.insert(doc);

오브젝트 업데이트
  
DBCollection coll = mongo.getCollection("tool_object");
BasicDBObject obj = new BasicDBObject("name", toolName);
DBObject modified = coll.findOne(obj);
DBObject useCnt = (DBObject) modified.get("use");
 
int cntDay = Integer.parseInt(useCnt.get("day").toString());
int cntMonth = Integer.parseInt(useCnt.get("month").toString());
int cntYear = Integer.parseInt(useCnt.get("year").toString());
 
useCnt.put("day", ++cntDay);
useCnt.put("month", ++cntMonth);
useCnt.put("year", ++cntYear);
 
modified.put("use", useCnt);
/* update( 이전정보의 오브젝트, 새로운 정보의 오브젝트 ) 로 인자 전달
coll.update(obj, modified);