Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Noob Problem (Java) check if a Document Exists inside my Collection

So i got a test Document inside my Collection

{
        "_id" : "testID",
        "memberID" : "testMemberID",
        "memberName" : "TestUser",
        "creationDate" : "25-05-2020"
}

Now i want to check if there already is a Document with the _id “testID” before creating it of course (Java). Or is there no need for something like this (are there no duplicates by default)

1 Like

Some general rules about the _id field:

The _id field is present in all documents in the collection - it is mandatory. If the _id is not supplied by the application / user, MongoDB will create it when the document is inserted (and it will be of type ObjectId). The _id value has a default unique index on it - this is automatically created by the MongoDB. So, a collection can have only one document with a specific _id. Also, the _id value cannot be modified for a document, and the unique index on this field cannot be deleted (or modified).


If you are creating a document, and if another document exists with the same _id, there will be an error and the new document will not be inserted (as it is considered as a duplicate). And, the error says something like "E11000 duplicate key error ...". The 11000 is the error code.

In Java, the concerned exception class is com.mongodb.MongoWriteException. And, the exception message is likely to be something like this: E11000 duplicate key error collection: test.test index: _id_ dup key: { _id: "testID" }

So, you can try one these following approaches, based upon your application needs:

  • Try to insert the document. If there is an exception (due to duplicate key), handle the exception; communicate with the user that the _id already exists.
  • Check if the document exists. If not exists, insert the document; communicate with the user that the document is inserted successfully. (Else don’t insert the document; communicate with the user that the document with the _id already exists).

Java code samples for both options:

Option 1:

/*
 * Returns a boolean true if document is inserted, else false.
 */
private boolean insertDocument() {

    Document doc = new Document("_id", "testID");
    
    try {
            collection.insertOne(doc);
    }
    catch(MongoWriteException e) {
        e.printStackTrace();
        if (e.getCode() == 11000) {
            System.out.println("You are trying to insert a document with *duplicate*  _id: " + doc.get("_id"));
        }
        else { 
            System.out.println("Some error while inserting document with  _id: " + doc.get("_id"));
        }
        return false;
    }
    
    System.out.println("Document inserted with value of _id: " + doc.get("_id"));
    return true;
}

Option 2:

private boolean insertDocument() {

    Document doc = new Document("_id", "testID");
    
    try {
        Document d = collection.find(eq("_id", doc.get("_id"))).first();
        
        if (d == null) {
            collection.insertOne(doc);
        }
        else {
            System.out.println("Document already exists with _id: " + doc.get("_id"));
            return false;
        }
    }
    catch(MongoWriteException e) {
        e.printStackTrace();
        System.out.println("Some error while inserting document with  _id: " + doc.get("_id"));
        return false;
    }

    System.out.println("Document inserted with value of _id: " + doc.get("_id"));
    return true;
}
1 Like

Thank you very much! Worked out

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.