How to update the whole object without changing the identifier in pymongo?

I am trying to update all the properties of a record / object that are stored in MongoDB, now I am trying to do this.

  • The object is deleted, but the identifier of the deleted object is saved.
  • Create a new object with the same identifier that I deleted.

Is it correct? or what to do on objects 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 the above code does not delete the object, it doc.deleted_countis 0.

+3
source share
2 answers

enter image description here

 from bson.objectid import ObjectId 
 def replace_one(record):
            result = client.test_db.test_collection.replace_one({"_id":ObjectId(record["_id"])}, record,upsert=True)
            print(result.matched_count)

What is the correct way to query MongoDB for _id using a string using Python?

Pymongo doc - http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one

+1
db.collection_name.update_one({"_id" : record["_id"]}, new_data}

$set, _id

+1

Source: https://habr.com/ru/post/1689760/


All Articles