Reputation: 457
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
}
}
Upvotes: 1
Views: 1597
Reputation: 46
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')
Upvotes: 1
Reputation: 457
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.
Upvotes: 1