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

后端 未结 2 772
鱼传尺愫
鱼传尺愫 2021-01-29 10:24

Is there any methods or packages, that can help me add auto increments to existing collection? Internet full of information, about how to add AI before you create collection, bu

2条回答
  •  迷失自我
    2021-01-29 11:15

    MongoDB does not have an inbuilt auto-increment functionality.

    Create a new collection to keep track of the last sequence value used for insertion:

    db.createCollection("counter")
    

    It will hold only one record as:

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

    Create a JavaScript function as:

    function getNextSequenceVal(seq_id){
       // find record with id seq_id and update the seq_val by +1
       var sequenceDoc = db.counter.findAndModify({
          query:{_id: seq_id},
          update: {$inc:{seq_val:1}},
          new:true
       });
    
       return sequenceDoc.seq_val;
    }
    

    To update all the already existing values in your existing collection, this should work (For the empty {}, you can place your conditions if you want to update some documents only):

    db.myCollection.update({},
       {$set:{'_id':getNextSequenceVal("mySequence")}},{multi:true})
    

    Now you can insert new records into your existing collection as:

    db.myCollection.insert({
       "_id":getNextSequenceVal("mySequence"),
       "name":"ABC"
    })
    

提交回复
热议问题