3

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.

ajayramesh
  • 3,576
  • 8
  • 50
  • 75

2 Answers2

2
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

daemon24
  • 1,388
  • 1
  • 11
  • 23
  • In pymongo 4.1.1 this produces "ValueError: update only works with $ operators". However, substituting "replace_one" for "update_one" in this answer works great. – Lee Richardson Jul 01 '22 at 13:55
1

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 string by using Python?

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

ajayramesh
  • 3,576
  • 8
  • 50
  • 75