MongoDB的CRUD操作(java Util )

來源:互聯網
上載者:User

標籤:

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 )

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.