简体   繁体   English

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

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

I have a JSON document in the following format,我有以下格式的 JSON 文档,

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

I need to update values of all the keys even nested (Ref,b,c,e) except _id to some default value say 'na' at once.我需要将除 _id 之外的所有键的值甚至嵌套(Ref、b、c、e)更新为某个默认值,例如“na”。 I think it is not possible using mongo Query.我认为使用 mongo 查询是不可能的。

Any way to do this in pymongo programmatically?有没有办法以编程方式在 pymongo 中做到这一点? Thanks in advance !!!提前致谢 !!!

Use a recursive function to Update values of all keys except _id to default value.使用递归函数将除 _id 之外的所有键的值更新为默认值。 Then use save() to update your documents.然后使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM