MongoDB Documentation, Release 3.0.4 { _id : 1, name : "Sarah C." } { _id : 2, name : "Bob D." } findAndModify Behavior 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. 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. Optimistic Loop 1. Create a function named insertDocument that performs the “insert if not present” loop. The function wraps the insert() method and takes a doc and a targetCollection arguments. Changed in version 2.6: The db.collection.insert() method now returns a writeresults-insert object that contains the status of the operation. Previous versions required an extra db.getLastErrorObj() method call. 3.3. MongoDB CRUD Tutorials 127 function insertDocument(doc, targetCollection) { while (1) {