PHP SDK version 2 - how do you know what the next document number should be?


Hello there.
I’m coming from a postgresql background where we have a “DEFAULT” keyword that will automatically insert your record with the next available number… assuming your table was created using a PK that’s set to auto increment.
I’m wondering how to do something similar with couchbase. I’ve manually added some documents that are called “audit_1” and “audit_2” but I’d like a way to programmatically assign these document names. Or maybe I need a complete paradigm shift. ??

I’ve been reading this:
But there’s not enough information there about how one goes about choosing a document id / document name.

Any tips would be appreciated.


If you leverage some of the KV capabilities along with N1QL, you can use an atomic ‘counter’ document as a place to maintain a sequence. It’s a bit different in that you’ll increment it first, but the cost is fairly cheap.

One other technique is to simply increment the number in the application and use the KV insert which will fail if the document already exists. This one is a bit more costly since if you have many PHP application servers and a high creation rate, you will use a lot of network IO. It’s fairly inexpensive on the server in processing, so this is a valid technique in situations where network IO is low-latency/high-throughput.


In addition to what @ingenthr suggested, you can use the UUID() function in N1QL to generate a primary key.


ok so, so far, I’ve been naming documents like this:


so perhaps I could do something like this:

  1. somehow select the latest record that matches the “automated_audit_?” pattern and then,
  2. parse the digit at the end. increment it by 1.
  3. use the integer from step 2 and use in with the “counter() method”… something like this:
    **counter(‘counter_id’, delta=1, initial=myvariable);

Does that sound reasonable?