skip to Main Content

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


  1. I guess this will solve your problem:

    values_to_update = ['abcd', 'abcdefg', 'ab']
    
    for new_val in values_to_update:
        doc = collection.find_one({'jk': 'some_key_for_query'})
    
        # if the document doesn't exist or new_val is longer than the existing value, perform the update
        if not doc or len(new_val) > len(doc.get('s', '')):
            collection.update_one({'jk': 'some_key_for_query'}, {'$set': {'s': new_val}}, upsert=True)
    
    Login or Signup to reply.
  2. Since you are using upsert, one option is to use update with pipeline, which allows to use the current values in the query:

    bulk_update.append(UpdateOne(query, 
      [{$set: {
          s: {$cond: [
              {$gte: [{$strLenCP: {$ifNull: ["$s", ""]}}, new_str_length]},
              "$s",
              new_string
          ]}
      }}],
      upsert=True))
    

    See how it works on the playground example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search