2015-10-07 78 views
1

我創建了一個簡單的java應用程序作爲我的大學迷你項目,其中我允許用戶執行插入,刪除,更新,搜索等操作的模塊之一 爲了驗證目的,我希望向用戶顯示錯誤消息如果他試圖刪除一個不存在於數據庫中的記錄,如 「對不起記錄未找到」我試過嘗試catch塊來檢查,如果mongodb拋出一個異常,如果文件未找到,但該功能工作...即時通訊全新以JAVA以及MongoDB的,所以我對這個問題的想法,有人可以幫我... 這裏是我的代碼的deleteActionPerformed和我的嘗試我如何檢查文檔是否存在使用Mongodb和JAVA?

private void deleteActionPerformed(java.awt.event.ActionEvent evt) {          
     try 
     { 

     DBCollection col=db.getCollection("activity"); //my collection name is activity 
     if(!Tid.getText().equals("")) //Tid is the TextField in which i am taking input of _id 
     { 
     col.remove(new BasicDBObject().append("_id",(Object)Tid.getText())); 
     } 
     else 
      JOptionPane.showMessageDialog(null,"Please Enter the ID"); 

     }catch(Exception e) 
     { 
      JOptionPane.showMessageDialog(null,"Record not Found "+e); 
     } 
    } 

try catch block dint作爲java或mongodb不會生成未找到的類型異常...

回答

0

這可能不是最有效的方法,但它應該工作。 我從我的一些代碼中找到了一個特定的文檔值(而不是_id)。可能有一個專門的_id方法。

/** 
* Checks if an activity exists with a given id. if no such activity exists 
* returns false. Returns true for one or more activities with a matching 
* id. 
* 
* @param db 
* @param id 
* @return boolean - true if one or more functions with matching names exit. 
*/ 
public static boolean activityExists(MongoDatabase db, ObjectId id) { 
    FindIterable<Document> iterable = db.getCollection("activity").find(new Document("_id", id)); 
    return iterable.first() != null; 
} 

編輯:它似乎最好使用計數方法。請參考以下回答https://stackoverflow.com/a/32509268/2520767

0

就你而言,使用find()+ limit()會顯着更快,因爲findOne()將始終讀取並返回文檔(如果存在)。 find()只是返回一個遊標(或不),並且只在遍歷遊標時纔讀取數據。

所以不是:

db.collection.findOne({_ ID:「身份識別碼」},{_id:1})

你應該使用:

db.collection.find( {_id:「myId」},{_id:1})。limit(1)

相關問題