I want to update a field in MongoDB only if the string value being inserted has a longer length (number of characters) than what is currently stored in the database. How can I achieve this?
Here is my current python code:
from pymongo import MongoClient, UpdateOne
# connect to client
...
query = {'jk': 'some_key_for_query'} # lookup in collection
d = {'s': 'abcd'} # field to update
bulk_update.append(UpdateOne(query, {'$set': d}, upsert=True))
# update
d = {'s': 'abcdefg'}
bulk_update.append(UpdateOne(query, {'$set': d}, upsert=True))
# don't update
d = {'s': 'ab'}
bulk_update.append(UpdateOne(query, {'$set': d}, upsert=True))
# bulk insert
...
During the first update, the field is set to ‘abcd’. In the second update, I expect the update to occur because the value ‘abcdefg’ has more characters than the current value in the database. However, I don’t want the third update to take place because the value ‘ab’ is shorter. How can I modify my code to achieve this behavior?
2
Answers
I guess this will solve your problem:
Since you are using upsert, one option is to use update with pipeline, which allows to use the current values in the query:
See how it works on the playground example