Pass upsert=True to find_one_and_replace() on Document.save() method. #2581
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Following the discussion found in #1944 (comment).
In my company, we have faced an edge case where we might have concurrent "save()" calls failing, please imagine the following situation:
If we have at least two processes running in parallel that tries to save a document with the same new
idin the same collection, both processes will getNonewhen invoking PyMongo'sfind_one_and_replacein this line because the document with such_iddoesn't exist in the collection, and then MongoEngine will invoke to PyMongo'sinsert_onehere, so one of these two processes will get the document inserted and the other will obtain aNotUniqueErrorexception raised.Instead, if we pass
upsert=Truetofind_one_and_replacemethod, we will make sure that the document is saved and won't fail, even more because conceptuallysave()should never fail with such exception, at least not for the unique index on_idfield. Also, note that we can ignore the returning value fromfind_one_and_replacesince all what we need to return is thedoc["_id"]that we already have in that trace.Note: I've tried to reproduce it in unit tests using a thread pool but it's quite hard :(