How to prevent duplication in update statement


I have documents like this in my MongoDB collection:

my_dict = {"chat": 1, "entity": 2, "count": 55}

I need to update them and if the document does not exist (entirely), then insert a new one:

                    {"$set": {"chat": 1,
                              "entity": 2,
                              "count": 60}},

But if the document exists, it is duplicating it! it should just update because chat and entity are the same. But it is inserting a new one.
So, I will be having two similar documents with differences in count only.

See how this is duplicated in the picture enter image description here,

I want the new one to replace the above one.

How can I do that?

Asked By: maria bandoria



You need to find the matching document. In your case, you can do it by the identical fields:

  {'chat': my_dict['chat'], 'entity': my_dict['entity']},
  {'$set': {'count': 60}},

The code in the original question is using my_dict to try to find the matching document to update, but my_dict includes the count, thus never finds the document and thus creating a new one…

Answered By: nimrod serok
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.