`insert_one` method changes passed item dictionary

11 views
Skip to first unread message

Михаил Топорков

unread,
May 14, 2018, 4:44:12 PM5/14/18
to mongodb-user
When calling method of collection `insert_one` and passing a dictionary as parameter, method changes passed dictionary outside of function scope by adding a field "_id" to said dictionary.


Expected behavior - passed dictionary remains unchanged outside function.
Actual behavior - passed dictionary changes outside function.


Version info:
Python 3.5
Motor 1.2.1

Wan Bachtiar

unread,
May 16, 2018, 10:23:15 PM5/16/18
to mongodb-user

Expected behavior - passed dictionary remains unchanged outside function.

Hi,

This question is more related to Python. In Python if you are passing a dictionary (mutable) to a function, and the function modifies the dictionary, the original dictionary will also be modified.

In this case, _id field was added as a reference identifier of that document within MongoDB collection. In most cases, this is a useful addition especially if there’s a requirement to find that document soon after.

Generally a way to preserve the original dictionary is to perform copy.deepcopy() on the dictionary before it’s passed to functions. However this comes with its own overhead. This may or may not be suitable for your use case.

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages