Skip to content

Instantly share code, notes, and snippets.

@pestilence669
Last active November 29, 2016 09:32
Show Gist options
  • Save pestilence669/7189df6177b742042302 to your computer and use it in GitHub Desktop.
Save pestilence669/7189df6177b742042302 to your computer and use it in GitHub Desktop.
Monotonic increasing sequences in MongoDB
// vim: set ts=4 sw=4 noet:
// create a collection to hold the named sequences
db.createCollection('counters');
// shell helper. initialize, if necessary, and return the next sequence
function getCounterFor(name) {
return db.counters.findAndModify({
query: { _id: name },
update: { $inc: { sequence: 1 } },
upsert: true,
new: true
}).sequence;
}
@tomwidmer
Copy link

N.B. for a non-sharded collection, you can just use a Timestamp field - it's in monotonic order even in the face of replicaset failover and clock skew (at least with MongoDB 3.2+)...

db.collection.insert({ts: new Timestamp(), data: "whatever"});

The server fills in the timestamp for you. If a server's clock is behind and takes over as primary, it keeps making timestamps in the same (future) second as the last TS from the old primary until its clock catches up (it has 32-bits worth of timestamps before it will run out). So you still get monotonic ordering.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment