PyMongo duplicate key error even set upsert True

36 Views Asked by At

I have a MongoDB document

{
    "_id": 12345,
    "a": "a",
    "hash": "1qaz2wsx"
}

I want to update specific "_id" that its "hash" is not the same

filter = {'_id': 12345, 'hash': {'$ne': '1qaz2wsx'}}
post = {'$set': {'c': 'c'}}

when I execute the command in Mongo Shell

db.test.updateOne({'_id': 12345, 'hash': {'$ne': '1qaz2wsx'}}, {'$set': {'c': 'c'}}, upsert=true)

It didn't throw an error and because the filter didn't match anything, so Mongo Shell return modifiedCount: 0

But when I run the same script using PyMongo

db.update_one(filter, post, upsert=True)

It throws the following error

pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: local.test index: _id_ dup key: { _id: 12345 }, full error: {'index': 0, 'code': 11000, 'keyPattern': {'_id': 1}, 'keyValue': {'_id': 12345}, 'errmsg': 'E11000 duplicate key error collection: local.test index: _id_ dup key: { _id: 12345 }'}

How can I solve this? And why these two behave differently

0

There are 0 best solutions below