I found an answer on this page. I’m guessing your code looks something like this (greatly simplified)?:
doc = {}
for i in xrange(2):
doc['i'] = i
collection.insert(doc)
The problem is that PyMongo injects an _id field into the document, if the _id
field does not exist, before inserting it (_id
is always generated client side with 10gen drivers). That means that the first time through the loop _id
is added by the insert method. Since doc
is defined outside the loop, each subsequent pass through the loop uses the same value for _id
.
Solution:
- Delete the key _id
for i in xrange(2):
doc['i'] = i
if '_id' in doc:
del doc['_id']
collection.insert(doc)
- Or create manually a new one:
from bson.objectid import ObjectId
for i in xrange(2):
doc['i'] = i
doc['_id'] = ObjectId()
collection.insert(doc)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…