Like many other database systems, Pymongo will add the unique identifier needed to retrieve data from the database as soon as it is inserted (what happens if you insert two dictionaries with the same content {'key1':'value1'} in the database? How would you distinguish what you want, and not from this?)
This is explained in the Pymongo docs :
When a document is inserted, the special key "_id" is automatically added if the document does not already have the key "_id". The value "_id" must be unique throughout the collection.
If you want to change this behavior, you can give the object the _id attribute before inserting. In my opinion, this is a bad idea. This will easily lead to collisions, and you will lose the juicy information that is stored in the βrealβ object , for example, the creation time , which is great for sorting and the like.
>>> a = {'_id': 'hello', 'key1':'value1'} >>> collection.insert(a) 'hello' >>> collection.find_one({'_id': 'hello'}) {u'key1': u'value1', u'_id': u'hello'}
Or if your problem occurs when serializing in Json, you can use the utilities in the BSON module:
>>> a = {'key1':'value1'} >>> collection.insert(a) ObjectId('53ad6d59867b2d0d15746b34') >>> from bson import json_util >>> json_util.dumps(collection.find_one({'_id': ObjectId('53ad6d59867b2d0d15746b34')})) '{"key1": "value1", "_id": {"$oid": "53ad6d59867b2d0d15746b34"}}'
(you can check that this is valid json on pages like jsonlint.com )
source share