Python Pymongo 不更新现有文档

2024-10-05 10:41:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用以下代码更新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”属性不存在,此更新应创建此属性并设置新值

我是做错了还是应该用其他函数来做

Python 3.7版

Pymango 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
    }
}

Tags: nameidtruenew属性mongodbokresult
2条回答

我认为必须在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(),而且很有效

相关问题 更多 >

    热门问题