【发布时间】:2020-03-23 17:14:55
【问题描述】:
Python 3.6.7
pymongo==3.10.1
每次启动我的应用程序时,我都需要维护一个给定的集合。我们可以更改之前加载的数据,也可以插入新数据。
我有以下代码:
from pymongo import UpdateOne
COLLECTION_NAME = 'profile'
data = [
UpdateOne(
{ "type": "user"},
{ "$set": { "order": 1 , "active": True, "name.pt_br": "usuário"} },
upsert = True
),
UpdateOne(
{ "type": "consultant"},
{ "$set": { "order": 2 , "active": True, "name.pt_br": "consultor"} },
upsert = True
),
UpdateOne(
{ "type": "business"},
{ "$set": { "order": 3 , "active": True, "name.pt_br": "gestor"} },
upsert = True
)
]
def load(db):
db[COLLECTION_NAME].bulk_write(data)
return True
文档已存在于集合中。当调用 load() 方法时,我可以更新任何属性。
但如果我需要包含一个新文档(类型:“x”)将其附加到data[],例如:
data = [
UpdateOne(
{ "type": "user"},
{ "$set": { "order": 1 , "active": True, "name.pt_br": "usuário"} },
upsert = True
),
UpdateOne(
{ "type": "consultant"},
{ "$set": { "order": 2 , "active": True, "name.pt_br": "consultor"} },
upsert = True
),
UpdateOne(
{ "type": "business"},
{ "$set": { "order": 3 , "active": True, "name.pt_br": "gestor"} },
upsert = True
),
UpdateOne(
{ "type": "x"},
{ "$set": { "order": 4 , "active": True, "name.pt_br": "x"} },
upsert = True
)
]
我收到以下错误:
File "/data/dev/python/myapp/software/app/lib/storages/mongodb/dataLoad/profile.py", line 30, in load
db[COLLECTION_NAME].bulk_write(data)
File "/home/kleysonr/.virtualenvs/graphql/lib/python3.6/site-packages/pymongo/collection.py", line 502, in bulk_write
bulk_api_result = blk.execute(write_concern, session)
File "/home/kleysonr/.virtualenvs/graphql/lib/python3.6/site-packages/pymongo/bulk.py", line 511, in execute
return self.execute_command(generator, write_concern, session)
File "/home/kleysonr/.virtualenvs/graphql/lib/python3.6/site-packages/pymongo/bulk.py", line 349, in execute_command
_raise_bulk_write_error(full_result)
File "/home/kleysonr/.virtualenvs/graphql/lib/python3.6/site-packages/pymongo/bulk.py", line 140, in _raise_bulk_write_error
raise BulkWriteError(full_result)
pymongo.errors.BulkWriteError: batch op errors occurred
如何根据data[] 变量进行插入/更新?
【问题讨论】: