0

I need to update a field of a Document if such field is None, but I don't want to overwrite it if such field has a value.

Right now I'm doing the following:

p = Person.objects(name="Foo").first()
if p.address is None:
    p.update(set__address="Bar Street, NY")

but it's not an atomic operation.

What I would like to do is something like:

Person.objects(name="Foo").update_one(set__address_if_none="Bar Street, NY")

but I can't seem to find anything about it on the web.

Is there anything like this, or a different way I could achieve this?

fabio.sang
  • 835
  • 8
  • 26

1 Answers1

2

Something like this?

Person.objects(name="Foo", address=None).update(set__address="Bar Street, NY")

Although as far as I'm aware this is not atomic as well. I mean it is atomic on a single document, but not on the collection. To be truely atomic you would need a transaction which Mongo seems to support now.

freakish
  • 54,167
  • 9
  • 132
  • 169