PS: I only have to do this due to business requirements
I’m able to achieve it using mongosh, but since there are multiple records to be updated, I’m trying to implement a simple python script to automate the task.
Is it possible to do this with pymongodb?
JavaScript
x
12
12
1
// store the document in a variable
2
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})
3
4
// set a new _id on the document
5
doc._id = ObjectId("4c8a331bda76c559ef000004")
6
7
// insert the document, using the new _id
8
db.clients.insert(doc)
9
10
// remove the document with the old _id
11
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})
12
I’m not able to set the new Id in the doc variable in order to insert the new document that will mirror the old one.
Thanks
Advertisement
Answer
Here’s a pymongo equivalent:
JavaScript
1
20
20
1
from pymongo import MongoClient
2
from bson import ObjectId
3
4
db = MongoClient()['mydatabase']
5
6
old_doc_id = '4cc45467c55f4d2d2a000002'
7
new_doc_id = '4c8a331bda76c559ef000004'
8
9
doc = db.clients.find_one({'_id': ObjectId(old_doc_id)})
10
11
if doc is not None:
12
# set a new _id on the document
13
doc['_id'] = ObjectId(new_doc_id)
14
15
# insert the document, using the new _id
16
db.clients.insert_one(doc)
17
18
# remove the document with the old _id
19
db.clients.delete_one({'_id': ObjectId(old_doc_id)})
20