user3243499
user3243499

Reputation: 3151

How to put an existing record in the MongoDB so that no new document is created?

How to efficiently post a document to MongoDB without checking if it is already in the collection. Currently, in my JAVA code, I am checking for the existence of document first and then if it is not where I post it. It seems this is very slow because for every document I am placing two queries.

Can't it be possible to just post the document and MongoDB handle it automatically that if there is already an existing document, just overwrite it else create a new document?

My document structure:

{
    "_id": "my unique id string",
    "name": "name1",
    "Address":{
       "street": "street 1",
       "country": "NZ",
    }
}

I am checking the existence of a document by comparing the "_id" field.

Upvotes: 0

Views: 842

Answers (3)

Andrea Di Cesare
Andrea Di Cesare

Reputation: 1253

With RESTHeart all write requests have upsert semantic: a request inserts a document into the collection (if it does not already exist) or updates it (if it does).

In order to avoid a document to be updated if it already exists, you can use the ETag checking feature of RESTHeart.

A request with the If-Match header only updates an existing document if its _etag property matches the specified value.

The following request fails with 412 Precondition Failed status code if the document /db/coll/docid exists:

POST /db/coll { "_id": "docid", "name": "name1", .. } If-Match:"etag"

Upvotes: 1

mturatti
mturatti

Reputation: 681

If you are using RESTHeart then PUT and POST methods implement the Mongodb's upsert semantics by default. See the Write Requests section in the docs.

Upvotes: 0

ernest_k
ernest_k

Reputation: 45319

You need to use the filter by which you find the document, then find and update the document. Using Java driver, you could do it like this:

Document filter = new Document("_id", "my unique id string");
Document update = new Document("name", "name1")
                     .append("Address", "<other fields>");
Document oldDocument = database
                     .getCollection("collectionName")
                     .findOneAndUpdate(filter, update);

oldDocument will be null if no document matched the filter.

If you would like to insert the document in case it didn't exist, then you should upsert:

UpdateOptions uo = new UpdateOptions().upsert(true);
database.getCollection("collectionName")
             .updateOne(filter, update, uo);

The last method call will return a result object that will give you the new ID if the document was created.

Upvotes: 0

Related Questions