如何从具有{“ key”:[{“ A”:“ 1”},{“ B”:“ 2”}]]的字典中提取键?

时间:2019-08-20 10:15:06

标签: python mongodb pymongo

我有一个python字典,

dict = {
    "A": [{
        "264": "0.1965"
    }, {
        "289": "0.1509"
    }, {
        "192": "0.1244"
    }]
}

我在mongoDB中有一个集合,

{
    "_id": ObjectId("5d5a7f474c55b68a873f9602"),
    "A": [{
            "264": "0.5700"
        }, {
            "175": "0.321"
        }
    }

    {
        "_id": ObjectId("5d5a7f474c55b68a873f9610"),
        "B": [{
                "152": "0.2826"
            }, {
                "012": "0.1234"
            }
        }
}

我想看看dict中的键“ A”在mongodb中是否可用。如果是,我想遍历列表中的键,即

[{
    "264": "0.19652049960139123"
}, {
    "289": "0.1509138215380371"
}, {
    "192": "0.12447470015715734"
}]
}

并检查mongodb中是否有264可用,并更新键值,否则追加。

mongodb中的预期输出:

{
"_id": ObjectId("5d5a7f474c55b68a873f9602"),
"A": [{
        "264": "0.1965"
    }, {
        "175": "0.321"
    }, {
        "289": "0.1509"
    }, {
        "192": "0.1244"
    }
}

{
    "_id": ObjectId("5d5a7f474c55b68a873f9610"),
    "B": [{
            "152": "0.2826"
        },{
            "012": "0.1234"
     }
    }

键264的值已更新。请帮助。

2 个答案:

答案 0 :(得分:0)

假设您要查找python部分而不是mongoDB,请尝试:

ORDER BY CASE WHEN IsCore = 1 THEN 0 ELSE 1 END,
         CASE WHEN IsCore = 1 THEN SortOrder END,
         Description;

答案 1 :(得分:0)

假设您的mongodb集合称为your_collection

   data= your_collection.find_one({'A':{'$exists':1}})

   if data:
       #loop over the keys
       for item in data['A']:
           #check whether a certain key is available
           if 'some_key' not in item:
               do_something()# update