我有一個現有的python方法正在MongoDB中正確執行更新操作。我得到了一個要求,如果在mongodb中修改了任何文檔,我需要在同一個集合中創建一個新的文檔用於審計目的。所以我在現有方法下面添加了一段代碼來執行插入操作。mongo_connector.errors.OperationFailed:insertDocument ::引起:: 11000 E11000重複鍵錯誤索引
self.mongo[db][coll].insert(update_spec)
,因爲我通過現有文檔的相同的ObjectId我的插入操作與下面的異常失敗,
mongo_connector.errors.OperationFailed: insertDocument :: caused by :: 11000 E11000 duplicate key error index: mongotest1.test.$_id_ dup key: { : ObjectId('57dc1ef45cc819b6645af91d') }
有沒有辦法忽略現有文檔的ObjectId,讓我可以在我新插入的文檔中插入其他現有值?請建議。以下是完整的代碼。
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
有沒有辦法可以從update_spec中刪除ObjectId類型的_id字段。我需要再次將update_spec插入到集合中。請建議。下面是我用過的代碼,但刪除條件不起作用。 self.mongo [db] [coll] .remove({update_spec [_id]:{「$ type」:7}}) self.mongo [db] [coll] .insert(update_spec) – Prasanna