使用pymongo将json文档的所有值更新为默认值

时间:2015-05-04 12:15:14

标签: python json mongodb pymongo

我有一个JSON文档,格式如下,

{
    "_id": ObjectId("54a2462820fb5b6068b45b05"),
    "Ref": 1,
    "a": {
        "b": "value1",
        "c": "value2",
        "d": {
            "e": "value3"
        }
    }
}

我需要更新所有键的值,甚至嵌套(Ref,b,c,e)除了_id到某个默认值,比如说' na'立刻。我认为使用mongo Query是不可能的。

以编程方式在pymongo中执行此操作的任何方法?在此先感谢!!!

1 个答案:

答案 0 :(得分:1)

使用递归函数将除_id之外的所有键的值更新为默认值。然后使用save()更新您的文档。

def recurse_keys(document):
    for key in document.keys():
        if isinstance(document[key], dict):
            recurse_keys(document[key])
        else:
            if key != '_id':
                document[key]='NA'


//update your document, save behaves as upsert with '_id' supplied.
db.collection.save(document)