How do i check whether the document exists using Mongodb and JAVA?

I have created a simple java application as my college mini project in which one of the module i am allowing users to perform operations like insert,delete,update,search For validation purposes i want a to display an error message to the user if he tries to delete a record which is not present in the DB like "Sorry record not found" I have tried try catch block to check that if mongodb throws a exception if document not found but that dint worked... i m completely new to JAVA as well as Mongodb so i have no idea about it ,can someone please help me... Here's my code of deleteActionPerformed and of what i tried

 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);
        }
    }   

The try catch block dint worked as java or mongodb is not generating a not found type exception...


This may not by the most efficient method, but it ought to work. I adapted it from some code of mine looking for a particular document value (other than _id). There may be a specialized method for _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;
}

EDIT: It seems that it is best to use the count method. Please refer to the following answer https://stackoverflow.com/a/32509268/2520767.


In your case, it is significantly faster to use find() + limit() because findOne() will always read + return the document if it exists. find() just returns a cursor (or not) and only reads the data if you iterate through the cursor.

So instead of:

db.collection.findOne({_id: “myId”}, {_id: 1})

you should use:

db.collection.find({_id: “myId”}, {_id: 1}).limit(1)