javascript - How to add auto increment to existing collection in mongodb/node.js? -


is there methods or packages, can me add auto increments existing collection? internet full of information, how add ai before create collection, did not find information on how add ai when collection exist...

mongodb not have inbuilt auto-increment functionality.

create new collection keep track of last sequence value used insertion:

db.createcollection("counter") 

it hold 1 record as:

db.counter.insert({_id:"mysequence",seq_val:0}) 

create javascript function as:

function getnextsequenceval(seq_id){    // find record id seq_id , update seq_val +1    var sequencedoc = db.counter.findandmodify({       query:{_id: seq_id},       update: {$inc:{seq_val:1}},       new:true    });     return sequencedoc.seq_val; } 

to update existing values in existing collection, should work (for empty {}, can place conditions if want update documents only):

db.mycollection.update({},    {$set:{'_id':getnextsequenceval("mysequence")}},{multi:true}) 

now can insert new records existing collection as:

db.mycollection.insert({    "_id":getnextsequenceval("mysequence"),    "name":"abc" }) 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -