KOVA
Docs

Autoincrement

A field that fills itself. The last number handed out is a row you can read and edit.

The counter belongs to the collection. _id stays an ObjectId. You name the extra field. The next insert that omits it stores the next integer.

Declare it

db.getSiblingDB("shop").runCommand({
  create: "orders",
  autoincrement: "id"
})

autoincrement is one field name, or a list of names. Each name is a single identifier, without a dot.

db.runCommand({
  create: "orders",
  autoincrement: ["id", "ticket"]
})

Create writes a row in admin.counters and adds a unique index on that field when no index already covers it exactly. The unique index still refuses a duplicate.

db.getSiblingDB("admin").counters.find({ collection: "shop.orders" })
{ _id: "shop.orders.id", collection: "shop.orders", field: "id", last: 0 }

last is the number already handed out. 0 means nothing has been issued. The _id of the row is database.collection.field.

What an insert does

db.orders.insertOne({ sku: "kettle" })
db.orders.insertOne({ sku: "mug" })

The first document stores id: 1 and last becomes 1. The second stores id: 2. The value is an int when it fits in 32 bits, and a 64-bit int after that.

A value you send is kept. When it is higher than last, last moves up to it.

db.orders.insertOne({ sku: "bowl", id: 50 })

That document keeps id: 50. The next insert that omits id stores 51. A lower value you send is kept too, and last stays where it was. The unique index rejects a duplicate of a number already stored.

Move the counter by hand

db.getSiblingDB("admin").runCommand({
  update: "counters",
  updates: [{
    q: { _id: "shop.orders.id" },
    u: { $set: { last: 10 } },
    multi: false
  }]
})

The next insert that omits id stores 11. Set last to 500 and the next insert stores 501. The row is ordinary catalog data: a checkpoint, a restart, and a Kova backup keep it.

From a SQL restore

A serial, bigserial, smallserial, AUTO_INCREMENT, identity, or DEFAULT nextval column becomes an autoincrement field when you restore that dump. The numbers already in the file stay in the field. SELECT pg_catalog.setval('seq', n, called) sets last:

A dump with neither setval nor a counter row sets last to the highest value already stored. Restore details are on Backup and restore.

Across shards

Each process keeps its own admin.counters. create on a router starts every shard at last: 0. An insert advances only the shard that stores the document. Two shards can hand out the same number. The unique index is local to the shard that holds the document. Use autoincrement on one process, or treat the numbers as per-shard sequences. A find of admin.counters through the router keeps one row per _id, so it shows a single last for that name.