mongodbrestheart

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.


Solution

  • 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"