Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Creating/updating record conditionally?

39 views
Skip to first unread message

Daniel Bernstein

unread,
Mar 14, 2022, 6:19:11 AM3/14/22
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 Document.save() 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?

Thanks!

Daniel Bernstein

unread,
Mar 15, 2022, 10:21:30 AM3/15/22
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
Forward
0 new messages