0

Consider this example:

f = {'a': 'b'}
col.insert(f)
print f

, where col is a mongodb collection.

The above code will print something among the lines of:

{'a': 'b', '_id': ObjectId('5278bc183e8b1310247e047b')}

I know why mongo needs to add the _id field when inserting the document into the collection, but I don't understand why it has to modify the dictionary I pass as an argument. I would like my dictionary f to remain unmodified.

I know I can just del f['_id'] after the insert, but is there any argument I can pass to insert that will make it not modify my dict?

4

2 回答 2

3

Simply set the manipulate argument to False, e.g.:

col.insert(f, manipulate=False)

See http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert

于 2013-11-05T09:59:44.463 回答
1

If I understand the documentation on the insert method correctly, manipulate parameter is what you're looking for:

If manipulate is True, the document(s) are manipulated using any SONManipulator instances that have been added to this Database. In this case an "_id" will be added if the document(s) does not already contain one and the "id" (or list of "_id" values for more than one document) will be returned. If manipulate is False and the document(s) does not include an "_id" one will be added by the server. The server does not return the "_id" it created so None is returned.

于 2013-11-05T10:00:23.363 回答