移位字段值

2024-09-25 08:24:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份文件:

{
    "_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来表达这一点,也不知道这是否是完成任务的一种切实可行的方式。你知道吗


Tags: toidqueryobjectidcopytag1tagidlocation3
1条回答
网友
1楼 · 发布于 2024-09-25 08:24:41

我想出了一个可能不是最优雅的解决方案,但它是有效的:

我的职能变成:

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)

相关问题 更多 >