Uploaded image for project: 'Documentation'
  1. Documentation
  2. DOCS-861

Clarify behavior of findAndModify with upsert

      If several clients dispatch a findAndModify command on the same target collection, under certain circumstances, multiple documents may be inserted. The simplest case to understand is when all of the findAndModify commands are issued with identical match criteria, say

      { name: "andy" }

      . Suppose that initially, no document with

      { name : "andy" }

      exists, and there is no unique index on the "name" field. In this case, if several of the findAndModify commands complete the "find" phase of the operation before any engage in the "modify" phase, those instances of the command may all choose to perform an insert of a new document, since no matching document was found. This is the same as the behavior of "update" operations with upsert behavior.

      In the above example, had there been a unique index on the "name" field, each fAndM command instance would have seen one of the following behaviors:

      • Exactly one fAndM execution would successfully insert a new document.
      • Zero or more fAndMs would update the document inserted by the inserter.
      • Zero or more fAndMs would fail when they attempted to insert a duplicate.

      To implement, for example, a counter with fAndM, use a unique index on the identifying field (like the name), and if an fAndM fails due to unique index constraint violation, simply repeat it. It will not fail due to this race multiple times, unless there is a process deleting counter documents.

            Assignee:
            kay.kim@mongodb.com Kay Kim (Inactive)
            Reporter:
            schwerin@mongodb.com Andy Schwerin
            Votes:
            1 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved:
              11 years, 11 weeks, 1 day ago