mongodb - Updating fields efficiently without losing data -
i'm getting feet wet pymongo, , seems easy task i'm not sure best way it.
i have dictionary of member
objects, each of has dictionary (key-value pairs of data). go through dictionary of member
objects, , update database:
- writing every field present in
member
object db, and - leaving unchanged other fields present in db member id not present in
member
object.
here's best shot, running extremely slow, i'm guessing there's better way. (maybe one-liner?)
in code, self.members
dictionary of members i'm iterating through, , member.structure()
returns dictionary of member
object's data.
for m in sorted(self.members.values(), key=lambda val:val.session) : ## each member if mcollection.find_one({'id':m.id}) none: ## if there no db entry matching member id print("\tmember {0} wasn't present in db. inserting.".format(m.id)) mcollection.insert(m.structure()) ## insert full dictionary else: ## if there matching db entry (k,v) in m.structure().items(): ## each entry in member's dictionary mcollection.update( {'id':m.id}, {'$set': {k:v}}, upsert=true ) ## set member's field value given in dictionary
for (k,v) in m.structure().items(): ## each entry in member's dictionary mcollection.update( {'id': 'm.id'}, {'$set': {k:v}}, upsert=true ) ## set member's field value given in dictionary
yes, insane. every k/v pair make separate request! should setting them @ once.
mcollection.update( {'id': 'm.id'}, {'$set': m.structure()})
Comments
Post a Comment