標籤:
1、儲存插入操作:
public static synchronized String insert(DBObject record) { DBCollection col = MongoDB.getDBCollection(TABLE_NAME); record.put("time", new Date().getTime()); WriteResult result = col.insert(record); //當前插入表的_id return record.get("_id").toString(); }
注意:col.insert(record)執行成功後 record可以擷取_id 可以通過 record.get("_id")是否為空白判斷儲存是否為空白!
2、更新編輯操作:
public static synchronized int edit(DBObject record) { DBCollection col = MongoDB.getDBCollection(TABLE_NAME); // 檢查是否有對應的obj_id存在 BasicDBObject queryObj = new BasicDBObject(); queryObj.put("_id", record.get("_id")); DBCursor dc = col.find(queryObj); if (dc.count() < 1) { return NO_RECORD_EXIST; } // 儲存資料 record.removeField("_id"); WriteResult result = col.update(queryObj, new BasicDBObject("$set", record)); return result.getN(); }
注意:在更新資料前要將被更新的資料中_id移除掉 否則報錯,queryObj是更新的查詢條件,record是更新的記錄,record中不能包含_id...
3、刪除操作:
public static synchronized int del(DBObject record, OlaCloudContent olaCloudContent) { DBCollection col = MongoDB.getDBCollection(TABLE_NAME); // 檢查是否有對應的obj_id存在 DBCursor dc = col.find(record); if (dc.count() < 1) { return NO_RECORD_EXIST; }// 刪除資料 WriteResult result = col.remove(record); OpLog.AddOpLog(olaCloudContent.getUserName(), TABLE_NAME, "del_key", record.toString()); return result.getN(); }
4、查詢操作:
public static synchronized CorpusAnswerWrap find(DBObject record,DBObject sort,int limit){ CorpusAnswerWrap answerWrap = new CorpusAnswerWrap(); List<AnswerEntity> answerList = new ArrayList<AnswerEntity>(); DBCollection col = MongoDB.getDBCollection(TABLE_NAME); DBCursor dc = col.find(record).sort(sort); if(limit > 0){ dc.limit(limit); } answerWrap.setTotalCount(dc.count()); while(dc.hasNext()){ AnswerEntity entity = answerWrap.new AnswerEntity(); entity.setRecord(dc.next()); answerList.add(entity); } answerWrap.setDatas(answerList.toArray(new AnswerEntity[answerList.size()])); return answerWrap; }
MongoDB的CRUD操作(java Util )