2013/07/08 23:54
阅读数 2K

A Counters Collection

Use a separate counters collection to track the last number sequence used. The _id field contains the sequence name and the seq field contains the last value of the sequence.

  1. Insert into the counters collection, the initial value for the userid:

    db.counters.insert(     {         _id: "userid",         seq: 0     } )
  2. Create a getNextSequence function that accepts a name of the sequence. The function uses thefindAndModify() method to atomically increment the seq value and return this new value:

    function getNextSequence(name) {     var ret = db.counters.findAndModify(         {             query: { _id: name },             update: { $inc: { seq: 1 } },             new: true         } );         return ret.seq; }
  3. Use this getNextSequence() function during insert().

    db.users.insert( {     _id: getNextSequence("userid"),     name: "Sarah C." } ) db.users.insert( {     _id: getNextSequence("userid"),     name: "Bob D." } )

    You can verify the results with find():


    The _id fields contain incrementing sequence values:

    { _id : 1, name : "Sarah C." } { _id : 2, name : "Bob D." }



When findAndModify() includes the upsert: true option and the query field(s) is not uniquely indexed, the method could insert a document multiple times in certain circumstances. For instance, if multiple clients each invoke the method with the same query condition and these methods complete the find phase before any of methods perform the modify phase, these methods could insert the same document.

In the counters collection example, the query field is the _id field, which always has a unique index. Consider that the findAndModify() includes the upsert: true option, as in the following modified example:

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

If multiple clients were to invoke the getNextSequence() method with the same name parameter, then the methods would observe one of the following behaviors:

  • Exactly one findAndModify() would successfully insert a new document.
  • Zero or more findAndModify() methods would update the newly inserted document.
  • Zero or more findAndModify() methods would fail when they attempted to insert a duplicate.

If the method fails due to a unique index constraint violation, retry the method. Absent a delete of the document, the retry should not fail.

点击引领话题📣 发布并加入讨论🔥
0 评论
9 收藏