0

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
Prasanna
  • 141
  • 1
  • 3
  • 17
  • Is there a way that I can delete _id field of type ObjectId from update_spec. I need to insert the update_spec again into the collection. Kindly suggest. Below is the code I have used but remove condition is not working. self.mongo[db][coll].remove({update_spec[_id]:{"$type":7}}) self.mongo[db][coll].insert(update_spec) – Prasanna Sep 18 '16 at 19:36

1 Answers1

0

Delete the id field from the update_spec object before inserting. The specific way to do this depends on which field of update_spec is the id, and what object type it is.

Andy Ray
  • 30,372
  • 14
  • 101
  • 138
  • Thanks for the suggestion. Below is the format of update_spec update_spec: {'_id': ObjectId('57dc1ef45cc819b6645af91d'), 'empname': 'qewreqwewq', 'empid': '12312'} – Prasanna Sep 18 '16 at 17:40
  • Andy, I tired like below but its not either removing the field from update_spec nor inserting values into the collection. Kindly let me know how to pass update_spec to remove ObjectId field. self.mongo[db][coll].remove({"_id":{"$type":7}}) self.mongo[db][coll].insert(update_spec) – Prasanna Sep 18 '16 at 18:52