How to set an auto-increment ID

Hi, all

Does there have any way to set an auto-increment ID?

I want to insert some logs into couchbase at any time and I want to make sure the document is unique or incremental.

I found this post : Auto-increment ID

But I don’t know what is incr() operation?

Here is my solution that I add a view to map all document and reduce it with _count function.

I get the view result in the beginning while connecting to Couchbase.

Since then I got the total count of documents and I could continue to add new item with an unique key.

Does there have any better solution?

@agau9527, the incr() operation Michael was referring is available in the 2.x Java SDK as counter(...) variations.
See the doc here.

The idea is that Couchbase has the notion of counter documents that can be incremented or decremented atomically.

So there’s no need for a view (which is less performant anyway), just use a separate counter document to generate your IDs (think of it like a Sequence in RDBMS if you will). Construct an ID by appending the value obtained from the counter to other parts of the key as you see fit.

For example, to get the key “FRA::User12345”:

//get relevant dynamic data (here the user's country code) from the `JsonObject` content you prepared: 
String prefix = content.getString("countryCode"); //gives "FRA"
//append separator and "User" prefix:
prefix = prefix + "::User";
//atomically get the next sequence number:
// increment by 1, initialize at 0 if counter doc not found
long nextIdNumber = bucket.counter("idGeneratorForUsers", 1, 0); //gives 12345
String id = prefix + nextIdNumber; //gives "FRA::User12345"
//you're now ready to save your document:
bucket.insert(JsonDocument.create(id, content));

how can i increment the value of counter using couchbase php sdk. I have php sdk 2.0.7. I am building a chat application and i used counter as my document key. I am using socket.io

@raushankumar can you open a new question tagged with PHP please? That will help for others to find it as well (@brett19)