简体   繁体   中英

Python Pymongo is not updating an existing document

I am trying to update an existing document in MongoDB with the code below:

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

My print returning:

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

But my data on MongoDB still without this property.

Additional info: "TYPE" attribute doesn't exists, this update should create this attribute and set new value.

Am I doing something wrong or should I use other function to do that?

Python 3.7

Pymongo 3.9.0

Thanks!!

Document:

{
    "_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
    }
}

I think you have to insert a document as the first parameter into the update_one method.

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

just added cast int() and str() before variables, and it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM