Today I Learned: 20/04/2025 - pymongo insert operation modifies the input
Publish date: 20 Apr 2025
Like much of this site, this is a note to myself to remember that the insert_one method of a pymongo client modifies the input dictionary to add an _id key if it doesn’t contain one:
from pymongo import MongoClient
client = MongoClient(...)
d = {"a": 1, "b": 2}
print(d)
client['db']['collection'].insert_one(d)
print(d)
yields this result:
{'a': 1, 'b': 2}
{'a': 1, 'b': 2, '_id': ObjectId('68054685b245fb3775304c31')}