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

后端 未结 2 771
鱼传尺愫
鱼传尺愫 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 10:54

    MongoDB reserves the _id field in the top level of all documents as a primary key. _id must be unique, and always has an index with a unique constraint. It is an auto-incrementing field. However, it is possible to define your own auto-incrementing field following the tutorial in the MongoDB documentation.

    Tutorial link: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/

    0 讨论(0)
  • 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"
    })
    
    0 讨论(0)
提交回复
热议问题