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

Update all the values of the json document to default value using pymongo

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

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

我需要更新所有键的值,甚至嵌套 (Ref,b,c,e) 除了 _id 到一些默认值,比如 'na' 一次。我认为使用 mongo 查询是不可能的。

有什么方法可以在 pymongo 中以编程方式执行此操作?提前致谢!!!

使用递归函数将除_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)