Python Pymongo不会更新现有文档

时间:2019-11-22 13:04:00

标签: python python-3.x mongodb pymongo pymongo-3.x

我正在尝试使用以下代码更新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

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

2 个答案:

答案 0 :(得分:1)

我认为您必须将文档作为第一个参数插入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')

答案 1 :(得分:1)

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')

只在变量之前添加了强制转换int()和str(),就可以了。

相关问题