Alex Rivera | Logout

How do I conditionally upsert a document in mongo?

Asked 2012-12-07T15:30:51.693
16

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.

Edit
Report

1 Answer

1

If WPCoder's response with and upsert=True isn't what you're looking for, than you may need $setOnInsert, which isn't implemented yet: https://jira.mongodb.org/browse/SERVER-340. It should be implemented for 2.4.0.

answered 2012-12-07T19:50:20.787

Your Answer