簡體   English   中英

Python Pymongo 未更新現有文檔

[英]Python Pymongo is not updating an existing document

我正在嘗試使用以下代碼更新 MongoDB 中的現有文檔:

def insert_data(conn, documents):
    for document in documents:
        new_document = document.split(',')
        result = conn.update_one({ '_id': new_document[0] },
                        { '$set': { "type": new_document[1] } }, upsert=True)
        print(result.raw_result)
    return print('Done')

我的打印返回:

{'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True}
{'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True}
{'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True}
{'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True}
{'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True}

但是我在 MongoDB 上的數據仍然沒有這個屬性。

附加信息:“TYPE”屬性不存在,此更新應創建此屬性並設置新值。

我做錯了什么還是應該使用其他 function 來做到這一點?

Python 3.7

Pymongo 3.9.0

謝謝!!

文檔:

{
    "_id" : 4,
    "name" : "Cultura",
    "broadcast" : "teste",
    "frequency" : "102.5",
    "modulation" : "FM",
    "protocol" : 8,
    "campaign" : 0,
    "status" : 0,
    "cmixCast" : null,
    "city" : {
        "id" : 2969,
        "name" : "Maringá"
    },
    "state" : {
        "id" : 16,
        "name" : "Paraná",
        "uf" : "PR"
    },
    "nodeId" : null,
    "__v" : 0,
    "utc" : -3,
    "ffmpeg" : 1,
    "newStation" : 0,
    "deletedAt" : "2019-09-27 17:31:41",
    "square" : 0,
    "musicalAction" : 0,
    "url" : "http://www.cultura.fm.br/",
    "observations" : null,
    "region" : {
        "id" : 5,
        "name" : "Sul"
    },
    "contacts" : [],
    "recorder" : {
        "queue" : 0.0,
        "status" : 0.0
    }
}

我認為您必須將文檔作為第一個參數插入到update_one方法中。

def insert_data(conn, documents):
    for document in documents:
        new_document = document.split(',')
        result = conn.update_one(document,
                        { '$set': { "type": str(new_document[1]) } })
        print(result.raw_result)
    return print('Done')
def insert_data(conn, documents):
    for document in documents:
        new_document = document.split(', ')
        result = conn.update_one({ '_id': int(new_document[0]) },
                        { '$set': { "type": str(new_document[1]) } })
        print(result.raw_result)
    return print('Done')

只需在變量之前添加 cast int() 和 str() ,它就可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM