Creating/updating record conditionally?

Skip to first unread message

Daniel Bernstein

Mar 14, 2022, 6:19:11 AMMar 14
to MongoEngine Users
Hi, all,

I'm trying to work with a collection where I need to override the existing document if the data I'm trying to insert has a newer timestamp field than what's in the collection currently, if any. My code is getting the updated entry as if it were completely new, so basically:
  • I have a class DocA(DynamicDocument), with a timestamp field in it.
  • When my code is called, I need to create an instance of DocA and try to insert it.
  • If the _id I'm using doesn't already exist, the document should be inserted
  • If the _id does exist, I should only insert if the new timestamp is newer than the existing entry.
I thought that the save_condition parameter of would be helpful here, but it's treating the document as brand new when I create it, and not even checking if save_condition was set. The documentation on save_condition is very light, but from what I can see it's really only useful for calling save on data already loaded from MongoDB, not a new Document class instance.

So... Is there a way to do what I'm trying to do atomically?


Daniel Bernstein

Mar 15, 2022, 10:21:30 AMMar 15
to MongoEngine Users
In case anyone else is trying to do something similar, I've found the following works.

DocA.objects(id='abc', timestamp__lt=<timestamp>).update(upsert=True, **data)

If the object doesn't exist, it will be inserted. If it exists and the new timestamp is newer, it will be updated. If it exists and the new timestamp is older than what's already in MongoDB, it will return no match and thus try to create an new entry, which will raise NotUniqueError because the id already exists.

Reply all
Reply to author
0 new messages