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

Clarify behavior of findAndModify with upsert

    XMLWordPrintable

Details

    • Bug
    • Status: Closed
    • Major - P3
    • Resolution: Fixed
    • None
    • mongodb-2.2
    • manual
    • None
    • true

    Description

      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.

      Attachments

        Issue Links

          Activity

            People

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

              Dates

                Created:
                Updated:
                Resolved:
                9 years, 42 weeks, 4 days ago