how to update entire object without changing the id in pymongo?

Viewed 2864

I am trying to update all properties of the record/object which is stored in MongoDB, now I am trying to do like this.

  1. Deleted the object, but keeping the ID of the object being deleted.
  2. Create a new object with the same ID which I have deleted.

Is it correct ? or What is they to do above objective using pymongo ?

mongo_object = {
 _id : 123,
 prop_key_1: some_value,
 // ... many present
 prop_key_n: some_value,
}

def delete(record):
    doc = get_db().reviews.delete_many({"id" : record["_id"]})
    print(doc.deleted_count)

# all key values are changed, mongo_object is changed except the id.


delete(mongo_object)
db.collection_name.insert_one(mongo_object)

But above code is not deleting the object, the doc.deleted_count is 0.

2 Answers
db.collection_name.update_one({"_id" : record["_id"]}, new_data}

just use update without $set , the document will get replaced completely without changing the _id

Related