2016-09-18 250 views
0

我有一个现有的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 
+0

有没有办法可以从update_spec中删除ObjectId类型的_id字段。我需要再次将update_spec插入到集合中。请建议。下面是我用过的代码,但删除条件不起作用。 self.mongo [db] [coll] .remove({update_spec [_id]:{“$ type”:7}}) self.mongo [db] [coll] .insert(update_spec) – Prasanna

回答

0

在插入之前,从update_spec对象中删除ID字段。具体做法取决于update_spec的哪个字段是id,以及它是什么对象类型。

+0

感谢您的建议。下面是格式update_spec update_spec:{'_id':ObjectId('57dc1ef45cc819b6645af91d'),'empname':'qewreqwewq','empid':'12312'} – Prasanna

+0

Andy, 我累得像下面,但它不是从update_spec中删除该字段,也不将值插入到集合中。请让我知道如何通过update_spec删除ObjectId字段。 self.mongo [db] [coll] .remove({“_ id”:{“$ type”:7}}) self.mongo [db] [coll] .insert(update_spec) – Prasanna