Last active
November 29, 2016 09:32
-
-
Save pestilence669/7189df6177b742042302 to your computer and use it in GitHub Desktop.
Monotonic increasing sequences in MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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+)...
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.