【问题标题】:How to check if a key in python dictionary exist in mongo db. If exist update the key value of that key in mongoDB如何检查 mongo db 中是否存在 python 字典中的键。如果存在,则更新 mongoDB 中该键的键值
【发布时间】:2019-12-20 02:21:06
【问题描述】:

我有一个 python 字典 结果= {'04BB30FC-5476-11DD-A31F-17FB9CFF4B22': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}, {'4531': '0.46331}4624'

key = 04BB30FC-5476-11DD-A31F-17FB9CFF4B22 和 [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}] 是键值。

我在 mongoDB 中有一个具有相同键和不同键值的文档。

collection = db["DOCUMENT"]

DOCUMENT={ "_id" : ObjectId("5d5270c4464cc8210eb5f683"), "ID" : "04BB30FC-5476-11DD-A31F-17FB9CFF4B22" : [ { "7173" : "0.4076433655407347" }, { "526" : " 0.3878485824518719" }]

我想做一个检查,如果在文档中找到结果中的 ID,则必须更新它,否则 upsert=T。

        for key in RESULT.keys():
        print(key)
        collection.update_one({"ID": key}, {"$set": RESULT}, upsert = True)

此代码仅插入新数据,无法更新,但追加导致重复。请帮助。

【问题讨论】:

    标签: pymongo


    【解决方案1】:

    您的示例恐怕有一些错误,但是我怀疑您将需要$exists 运算符。稍微整理一下,下面的代码就可以工作了。

    collection =db['DOCUMENT']
    #                                                                                                               You are missing "])" from the end --- v
    # RESULT = {'04BB30FC-5476-11DD-A31F-17FB9CFF4B22': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}, {'4531': '0.44331446284643317'}
    RESULT =   {'04BB30FC-5476-11DD-A31F-17FB9CFF4B22': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}, {'4531': '0.44331446284643317'}]}
    
    #                 You have a "double colon" in your JSON which is invalid --- v                                        v                                 You are missing "})" from the end --- v
    # db.document.insert_one({ "_id" : ObjectId("5d5270c4464cc8210eb5f683"), "ID" : "04BB30FC-5476-11DD-A31F-17FB9CFF4B22" : [ { "7173" : "0.4076433655407347" }, { "526" : "0.3878485824518719" }]
    collection.insert_one({"04BB30FC-5476-11DD-A31F-17FB9CFF4B22" : [ { "7173" : "0.4076433655407347" }, { "526" : "0.3878485824518719" }]})
    
    print(collection.find_one({}))
    
    for key in RESULT.keys():
        print(key)
        collection.update_one({key: {"$exists": True}}, {"$set": RESULT}, upsert = True)
    
    print(collection.find_one({}))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 2019-03-01
      • 2017-06-23
      相关资源
      最近更新 更多