'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'm allowing users to perform operations like insert, delete, update and search.

For validation purposes I want a to display an error message to the user if he tries to delete a record which isn't 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 didn't worked. I'm new in Java and Mongodb and need help.

Here's my code of deleteActionPerformed and of what I tried:

private void deleteActionPerformed(java.awt.event.ActionEvent evt) {
    try {
        // my collection name is activity
        DBCollection col = db.getCollection("activity");
        // Tid is the TextField in which i am taking input of _id
        if(!Tid.getText().equals("")) {
            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 is not generating a not found type exception.



Solution 1:[1]

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:

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ℛɑƒæĿᴿᴹᴿ
Solution 2 Ahmed Ashour