将json补丁应用于Mongoengine文档

时间:2018-11-23 10:20:32

标签: python json mongodb mongoengine json-patch

我正在尝试将一个json补丁应用于Mongoengine文档。

我正在使用以下json-patch库:https://github.com/stefankoegl/python-json-patch和带Python 3.6.3的mongoengine 0.14.3

这是我的实际代码:

json_patch = JsonPatch.from_string(jp_string)
document = Document.objects(id=document_id)
json_documents = json.loads(document.as_pymongo().to_json())
json_patched_document = json_patch.apply(json_documents[0])
Document.objects(id=document_id).first().delete()
Document
    .from_json(json.dumps(json_patched_document))
    .save(force_insert=True)

是否有更好的方法来保存已编辑的json文档?

我增强了一些代码:

json_patch = JsonPatch.from_string(jp_string)
document = Document.objects(id=document_id)
json_document = json.loads(document.as_pymongo().to_json())
json_patched_document = json_patch.apply(json_documents[0])
Document
    .from_json(json.dumps(json_patched_document), created=True)
    .save()

但是,有没有一种方法可以不将文档转换为json?

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,我不想保存完整的文档,只是想更新已修改/添加的字段。

这是我在以下输入中测试的代码:

def tryjsonpatch():
    doc_in_db = {'foo': 'bar', "name": "aj", 'numbers': [1, 3, 7, 8]}
    input = {'foo': 'bar', "name": "dj", 'numbers': [1, 3, 4, 8]}
    input2 = {'foo': 'bar', "name": "aj", 'numbers': [1, 3, 7, 8], "extera": "12"}
    input3 = {'foo': 'bar', "name": "dj", 'numbers': [1, 3, 4, 8], "extera": "12"}

    patch = jsonpatch.JsonPatch.from_diff(doc_in_db, input3)
    print("\n***patch***\n", patch)
    doc = get_minimal_doc(doc_in_db, patch)

    result = patch.apply(doc, in_place=True)
    print("\n###result###\n", result,
           "\n###present###\n", doc_in_db)


def get_minimal_doc(present, patch):
    cur_dc = {}
    for change in patch.patch:
        if change['op'] not in ("add"):
            keys = change['path'].split("/")[1:]
            present_move = {}

            old_key = 1
            first = True
            for key in keys:
                if key.isdigit():  # old_key represented a array
                    cur_dc[old_key] = present_move
                else:
                    if first:
                        cur_dc[key] = {}
                        first = False
                    else:
                        cur_dc[old_key][key] = {}

                    old_key = key
                    present_move = present[old_key]
    return cur_dc
tryjsonpatch()