发表于|更新于|编程Python
|总字数:217|阅读时长:1分钟|浏览量:|
近期项目开始使用 pymongo,遇到一对坑。
¶pymongo 使用过程中的坑
¶0x0 Question 1: 插入自动生成 _id
1 2 3
| db.collection.insert(array) db.collection.insert_one(array) db.collection.insert_many(array)
|
均会使 array 生成 mongodb 中的自增 ObjectId ,且使用
1 2
| for row in array: del row['_id']
|
无法进行删除!造成后续更新过程中的困扰。
¶Solution
由于 python 在传参过程中属于地址传递,所以会造成上述问题。可使用copy.deepcopy()生成副本后再进行插入操作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| ... import copy array=[ { 'name':'张三', 'age':10 }, { 'name':'李四', 'age':16 } ] try: iArray=copy.deepcopy(array) db.collection.insert(iArray) except Exception as eBatchInsert: pass ...
|
这样可以避免 array 中由于插入操作生成 _id 字段,导致后期更新等出现问题。