在不丢失数据的情况下有效地更新字段
Updating fields efficiently without losing data
我正在尝试使用 pymongo,这似乎是一项简单的任务,但我不确定最好的方法。
我有一个包含 Member
个对象的字典,每个对象都有一个字典(数据的键值对)。我想查看 Member
个对象的字典,并更新数据库:
- 将
Member
对象中存在的每个字段写入数据库,并且
- 保持数据库中存在于该成员 ID 的
Member
对象中不存在的任何其他字段不变。
这是我最好的拍摄,但是 运行 它 非常 慢,所以我猜有更好的方法。 (也许甚至是单线?)
在此代码中,self.members
是我正在遍历的成员字典,member.structure()
returns 是 Member
对象数据的字典。
for m in sorted(self.members.values(), key=lambda val:val.session) : ## for each member
if mcollection.find_one({'id':m.id}) is None: ## if there is no db entry matching the member id
print("\tMember {0} wasn't present in the db. Inserting.".format(m.id))
mcollection.insert(m.structure()) ## insert the full dictionary
else: ## if there is a matching db entry
for (k,v) in m.structure().items(): ## for each entry in the member's dictionary
mcollection.update( {'id':m.id}, {'$set': {k:v}}, upsert=True ) ## set the member's field to its value given in the dictionary
for (k,v) in m.structure().items(): ## for each entry in the member's dictionary
mcollection.update( {'id': 'm.id'}, {'$set': {k:v}}, upsert=True ) ## set the member's field to its value given in the dictionary
是的,这太疯狂了。对于每 k/v 对,您都提出一个单独的请求!你应该一次设置它们。
mcollection.update( {'id': 'm.id'}, {'$set': m.structure()})
我正在尝试使用 pymongo,这似乎是一项简单的任务,但我不确定最好的方法。
我有一个包含 Member
个对象的字典,每个对象都有一个字典(数据的键值对)。我想查看 Member
个对象的字典,并更新数据库:
- 将
Member
对象中存在的每个字段写入数据库,并且 - 保持数据库中存在于该成员 ID 的
Member
对象中不存在的任何其他字段不变。
这是我最好的拍摄,但是 运行 它 非常 慢,所以我猜有更好的方法。 (也许甚至是单线?)
在此代码中,self.members
是我正在遍历的成员字典,member.structure()
returns 是 Member
对象数据的字典。
for m in sorted(self.members.values(), key=lambda val:val.session) : ## for each member
if mcollection.find_one({'id':m.id}) is None: ## if there is no db entry matching the member id
print("\tMember {0} wasn't present in the db. Inserting.".format(m.id))
mcollection.insert(m.structure()) ## insert the full dictionary
else: ## if there is a matching db entry
for (k,v) in m.structure().items(): ## for each entry in the member's dictionary
mcollection.update( {'id':m.id}, {'$set': {k:v}}, upsert=True ) ## set the member's field to its value given in the dictionary
for (k,v) in m.structure().items(): ## for each entry in the member's dictionary
mcollection.update( {'id': 'm.id'}, {'$set': {k:v}}, upsert=True ) ## set the member's field to its value given in the dictionary
是的,这太疯狂了。对于每 k/v 对,您都提出一个单独的请求!你应该一次设置它们。
mcollection.update( {'id': 'm.id'}, {'$set': m.structure()})