Skip to content

Instantly share code, notes, and snippets.

@igor822
Created May 21, 2013 04:29
Show Gist options
  • Save igor822/5617484 to your computer and use it in GitHub Desktop.
Save igor822/5617484 to your computer and use it in GitHub Desktop.
Simple create auto increment mongo
// 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