The Python Oracle

Mongodb replace_one() with upsert = true throws duplicate key error

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
02:34 Accepted answer (Score 5)
03:15 Answer 2 (Score 1)
03:41 Answer 3 (Score 0)
04:10 Thank you

--

Full question
https://stackoverflow.com/questions/5491...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #mongodb #pymongo

#avk47



ACCEPTED ANSWER

Score 6


I have found the problem:

in this line of code:

db['dataitemdetails'].replace_one({
    'asset_Id': tdata['asset_id'],
    'period_type': tdata['period_type'],
    'detail_id': tdata['detail_id'],
    'currencycode': tdata['currencycode'],
    'dataitem_Id': tdata['dataitem_id'],
    'period_end': tdata['period_end'],
    'scenario_id': tdata['scenario_id'],
}, tdata, upsert=True)

my filter is wrong.

where asset_Id should have been asset_id, and dataitem_Id should be dataitem_id.

thus no match is found but when inserting a duplicate key error raised.




ANSWER 2

Score 2


To answer your first question,

If you don't provide _id field value for upsert=true, MongoDB will generate a new id

And the reason why you are getting the duplicate key error is, you haven't used the period field in your filter condition.




ANSWER 3

Score 0


You are telling mongodb to replace one document. Your filter is most likely returning multiple documents.

Use a find with the same filter and figure out a filter that will always return one document. In most cases just using an id should be enough to return one document so long as your schema is layed out correctly.