我有一份文件:
{
"_id" : ObjectId("53ebc91c5b8bb46c9683b022"),
"tagid" : "tag1",
"location1" : "shelf1",
"location2" : "shelf2",
"location3" : "shelf3",
"location4" : "shelf4",
"location5" : "shelf5",
}
一个功能:
def myfunction():
loc1 = {"location1": request.form.get('location')}
query = {"tagid": request.form.get('tag')}
tagid = handle.trackingdb.update(query,{"$set": loc1},**{'upsert':True})
如果myfunction获得一个新位置(shelfz),我怎样才能有效地将其插入到location1中,同时将其他字段值向下移动,使其看起来像是在下方,同时将字段保持在5个位置?
{
"_id" : ObjectId("53ebc91c5b8bb46c9683b022"),
"tagid" : "tag1",
"location1" : "shelfz",
"location2" : "shelf1",
"location3" : "shelf2",
"location4" : "shelf3",
"location5" : "shelf4",
}
我目前的想法是:
query tagid
copy location4 to location5
copy location3 to location4
copy location2 to location3
copy location1 to location2
insert location1
但是,我不确定如何用PyMongo表达这一点,或者它是否是完成任务的实用方法。
答案 0 :(得分:0)
我想出了一个可能不是最优雅的解决方案,但它确实有效:
myfunction成了:
def myfunction():
location = request.form.get('location')
query = {"tagid": request.form.get('tag')}
#get document as dictionary:
retrieve = handle.trackingdb.find_one(query)
#function replaces values of specified keys in a dict:
def replace_value(key_to_find, value):
for key in retrieve.keys():
if key == key_to_find:
retrieve[key] = value
#if the location has changed...:
if location != retrieve.get("location1", ""):
#shift all of the key values and insert the new one
replace_value("location5", retrieve.get("location4", ""))
replace_value("location4", retrieve.get("location3", ""))
replace_value("location3", retrieve.get("location2", ""))
replace_value("location2", retrieve.get("location1", ""))
replace_value("location1", location)
#update the document
tagid = handle.trackingdb.update({},retrieve)