I've got a document
{ key : 'key1', value : 'value1', update_time : 100 }
That I'd like to change only with more recent (greater) update times. What I'm doing now is:
def update_key1(new_value, new_time):
record = find_one( { key : 'key1' } )
if not record or record['update_time'] < new_time:
update( { key : 'key1', value : new_value, update_time : new_time }, upsert=True)
Obviously this is an extra roundtrip to the db, but more importantly there's no lock on the document, and concurrent calls could result in a lower new_time's value remaining in the db. Is there a way to perform an upsert only if a condition is true?
EDIT: Just to clarify, the intention is not to create multiple documents for each key and then sort on lookup. Though that would solve my problem, these values change a lot and would waste a lot of space.