Skip to content

Instantly share code, notes, and snippets.

@wpik
Last active August 20, 2019 12:37
Show Gist options
  • Select an option

  • Save wpik/dd22dd5e431d05cc3a9ce0b9f5f27087 to your computer and use it in GitHub Desktop.

Select an option

Save wpik/dd22dd5e431d05cc3a9ce0b9f5f27087 to your computer and use it in GitHub Desktop.
Mongo DB Auto Increment

Based on: https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm

  1. Create collection to store sequence numbers: db.createCollection("counters");

  2. Initialize the sequence: db.counters.insert({_id:"partySeq",sequence_value:-1});

  3. Define function to get next sequence value:

    function getNextSequenceValue(sequenceName){
    
       var sequenceDocument = db.counters.findAndModify({
          query:{_id: sequenceName },
          update: {$inc:{sequence_value:1}},
          new:true
       });
    
       return sequenceDocument.sequence_value;
    };
    
  4. Create index on seq field: db.parties.createIndex({seq:1},{background:true, sparse:true, unique: true});

  5. Enumerate the collection and assign sequence numbers:

    db.parties.find().sort({_id:1}).forEach(
    	function(p){
    		db.parties.update({_id: p._id}, {$set:{seq: getNextSequenceValue("partySeq")}})
    	}
    );
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment