I have an existing python method which is doing the update operation properly in mongodb. I got a requirement where if any document modified in mongodb, I need to create a new document in same collection for audit purpose. So I added below piece of code under existing method to perform insert operation.
self.mongo[db][coll].insert(update_spec)
As i'm passing same ObjectId of existing document to my insert operation its failing with below exception,
mongo_connector.errors.OperationFailed: insertDocument :: caused by :: 11000 E11000 duplicate key error index: mongotest1.test.$_id_ dup key: { : ObjectId('57dc1ef45cc819b6645af91d') }
Is there a way to ignore the ObjectId of existing document, so that I can insert the other existing values in my new inserted document? Kindly suggest. Below is the complete code.
def update(self, document_id, update_spec, namespace, timestamp):
"""Apply updates given in update_spec to the document whose id
matches that of doc.
"""
db, coll = self._db_and_collection(namespace
self.mongo[db][coll].insert(update_spec)
self.meta_database[meta_collection_name].replace_one(
{self.id_field: document_id, "ns": namespace},
{self.id_field: document_id,
"_ts": timestamp,
"ns": namespace},
upsert=True)
no_obj_error = "No matching object found"
updated = self.mongo[db].command(
SON([('findAndModify', coll),
('query', {'_id': document_id}),
('update', update_spec),
('new', True)]),
allowable_errors=[no_obj_error])['value']
return updated