I want to update the month of document in mongoDB. for example changing the "month": "June"
to "month": "May"
in the document that has "truck_id": "A01"
This are my documents in MongoDB:
{
"0": {
"available": "no",
"end_date": "10",
"month": "June",
"start_date": "15",
"truck_id": "A01"
},
"1": {
"available": "yes",
"end_date": null,
"month": "June",
"start_date": null,
"truck_id": "A02"
}
}
And this is the code in my API:
@app.route('/update', methods=["PUT"])
def updateElement():
object_id = request.get_json()
object_update = request.get_json()
query = SampleTable.update_one(object_id, object_update)
return jsonify(query)
When I tried to test my API with postman I write this in postmans raw body tester :
{
"0":{
"truck_id":"A01"
},
"$set":{
"month":"May"
}
}
But when I tried this get the error:
Traceback (most recent call last):
File "C:\Users\umut8\AppData\Local\Programs\Python\Python310\Lib\site-packages\flask\app.py", line 2091, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\umut8\AppData\Local\Programs\Python\Python310\Lib\site-packages\flask\app.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\umut8\AppData\Local\Programs\Python\Python310\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\umut8\AppData\Local\Programs\Python\Python310\Lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\umut8\AppData\Local\Programs\Python\Python310\Lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\umut8\AppData\Local\Programs\Python\Python310\Lib\site-packages\flask\app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "D:\Dev\api_test\appi\app.py", line 29, in updateElement
query = SampleTable.update_one(object_id, object_update)
File "C:\Users\umut8\AppData\Local\Programs\Python\Python310\Lib\site-packages\pymongo\collection.py", line 1023, in update_one
common.validate_ok_for_update(update)
File "C:\Users\umut8\AppData\Local\Programs\Python\Python310\Lib\site-packages\pymongo\common.py", line 567, in validate_ok_for_update
raise ValueError('update only works with $ operators')
ValueError: update only works with $ operators
I know probably many things I do in here is wrong and I probably ask my question in a bad way but I don't know how to solve this.
CodePudding user response:
Use replace_one()
instead of update_one()
. The 3rd parameter of replace_one()
is upsert
.
SampleTable.replace_one(object_id, object_update, True)
The exception was raised because you didn't specify any update operator e.g. $set
.