How do you implement an auto-incrementing primary ID in MongoDB?

后端 未结 7 1594
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 12:11

Just like in MYSQL, I want an incrementing ID.

7条回答
  •  感动是毒
    2020-12-05 12:55

    MongoDB provides 2 way to auto increment _id (or custom key) .

    • Use Counters Collection
    • Optimistic Loop

    Counter Collection


    Here we need to create collection which stores the maximum number of keys and increment by 1 every time when we call this function.

    1. STORE FUNCTION

    function getNextSequence(collectionName) {
       var ret = db.counters.findAndModify({
                   query: { _id: collectionName },
                   update: { $inc: { seq: 1 } },
                   new: true,
                   upsert: true
                 });
    
       return ret.seq;
    }
    

    2. INSERT DOC

    db.users.insert({
      _id: getNextSequence("USER"),
      name: "Nishchit."
    })
    

    Optimistic Loop


    In this pattern, an Optimistic Loop calculates the incremented _id value and attempts to insert a document with the calculated _id value. If the insert is successful, the loop ends. Otherwise, the loop will iterate through possible _id values until the insert is successful.

    1. STORE FUNCTION

    function insertDocument(doc, targetCollection) {
    
        while (1) {
    
            var cursor = targetCollection.find( {}, { _id: 1 } ).sort( { _id: -1 } ).limit(1);
    
            var seq = cursor.hasNext() ? cursor.next()._id + 1 : 1;
    
            doc._id = seq;
    
            var results = targetCollection.insert(doc);
    
            if( results.hasWriteError() ) {
                if( results.writeError.code == 11000 /* dup key */ )
                    continue;
                else
                    print( "unexpected error inserting data: " + tojson( results ) );
            }
    
            break;
        }
    }
    

    2. INSERT DOC

    var myCollection = db.USERS;
    
    insertDocument(
       {
         name: "Nishchit Dhanani"
       },
       myCollection
    );
    

    Official doc from MongoDB.

提交回复
热议问题