This pattern is a combination of an always-incrementing atomic counter (used as an ID), and a set of documents that use the ID in the key.
First you have to setup the counter-id, this can be done on app initialization.
There are some alternatives depending on the SDK you are using.
# initialize the counter
c = Couchbase.new # => setup default connection
c.set("user::count", 0) # => initialize counter
Each time you want to create a new item, you increment the counter-id and use it as a component of the key.
Follow the variable new_id through this Ruby code to see how it is initialized, and used as a value, and used in the document key.
# retrieve the latest (so you see incr adds one...)
c.get("user::count") # => 3
# increment the counter-id
new_id = c.incr("user::count") # => new_id = 4
# store the counter-id as a self-reference
user_hash = {
:uid => new_id,
:username => "jsmith",
:firstname => "John",
:lastname => "Smith"
}
# create the document with the counter-id and hash
c.add("user::#{new_id}", user_hash) # => save new user, with document key = "user::4"
Retrieve the document based on the ID.
In this case we are just getting the latest user created, but it could be anywhere from
counter-id = 1 to the current value of the counter-id (in this case 4).
# retrieve the latest
latest_user = c.get("user::count") # => latest_user = 4
# retrieve the document with the index
user_info = c.get("user::#{latest_user}") # => retrieve user document
puts user_info
# => { "uid" => 4, "username" => "jsmith", "firstname" => "John", "lastname" => "Smith" }