繁体   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