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; }
时间: 2024-10-11 10:18:30