Created
May 21, 2013 04:29
-
-
Save igor822/5617484 to your computer and use it in GitHub Desktop.
Simple create auto increment mongo
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
// Adding counter | |
db.counters.insert( | |
{ | |
_id: "userid", | |
seq: 0 | |
} | |
); | |
// function to add sequence | |
function getNextSequence(name) { | |
var ret = db.counters.findAndModify( | |
{ | |
query: { _id: name }, | |
update: { $inc: { seq: 1 } }, | |
new: true | |
} | |
); | |
return ret.seq; | |
} | |
// Testing | |
db.users.insert( | |
{ | |
_id: getNextSequence("userid"), | |
name: "Sarah C." | |
} | |
); | |
db.users.insert( | |
{ | |
_id: getNextSequence("userid"), | |
name: "Bob D." | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment