Skip to content

Instantly share code, notes, and snippets.

@hectorcorrea
Created June 30, 2013 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hectorcorrea/5895570 to your computer and use it in GitHub Desktop.
Save hectorcorrea/5895570 to your computer and use it in GitHub Desktop.
A quick way to get incremental ids for documents in MongoDB via the findAndModify feature. This snippet gets a new incremental/sequential ID. Keep in mind that this is not a good strategy when you database is horizontally distributed which is why MongoDB out of the box uses a much more complex algorithm to calculate _id. Use at your own risk. [S…
var getNewId = function(db, callback) {
var counters = db.collection('counters');
var query = {'name': 'myCustomId'};
var order = [['_id','asc']];
var inc = {$inc:{'next':1}};
var options = {new: true, upsert: true};
counters.findAndModify(query, order, inc, options, function(err, doc) {
if(err) {
callback(err);
return;
}
var id = doc.next;
callback(null, id);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment