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

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -