Duplicate document getting inserted

Hi,

I am trying to use Java SDK to upsert a document into Couchbase Server Community Edition installed locally. I use following statements to upsert document

JsonObject jo = JsonObject.fromJson(jsonString);
jDoc = JsonDocument. create( documentId ,jo);
bucket.upsert(jDoc);

I generate the document id prior to upsert operation as follows:

JsonLongDocument ctrDoc = bucket.counter( documentType,1,1);
Long ctr = ctrDoc.content();
documentId = documentType + ctr.toString();

The code works fine but when I log in to Couchbase Server, it inserts two documents. One correct document and another one with just a pre-fix of the documentId and a document number. See the attache screenshot

Can someone help?

Thanks in advanceDuplicate%20record

Hi @dilipapte

Yes it looks like that’s what that code will do. You have a bucket.counter(documentType, …) call, I assume documentType==“user_”, so that creates a “user_” document.

Then you create a documentId from documentType + the contents of the counter, e.g. “user_1”, and upsert a new document with that id.

All looks fine to me - am I missing something?

Thanks for your quick reply.

I do not want two documents to be created. I am using bucket.counter to generate next number and then using that to suffix with user_

How to avoid inserting two documents but generate id using counter to suffix it??

The counter is stored in a document itself. It doesn’t need to be prefixed with user_ but it needs to exist somewhere . You could give it a different name.

Thanks ingenthr.
Sorry, I am new to couchbase and did not get what you are suggesting.

I thought on order to generate unique id, you first need to call bucket.counter which just returns next counter for that type of document. Then you need to use this counter to suffix into unique id to be passed into bucket.upsert method.

I want to create a single document with next counter. How can I achieve this?

bucket.counter creates a document to store the counter though.

Do you actually need a counter? Using UUIDs can be an easy and cheap way to generate unique document IDs, without requiring the contention of a counter document.