AdR
AdR

Reputation: 305

Update multiple fields in mongo based on their existence

I am trying to copy selected fields from collection 'a' to collection 'b'. I would like to set multiple fields on b based on whether they exist in a. i.e If the field dosen't exist in 'a; then I don't want to set it in 'b'.

This is what I'm trying

b.update_one(
              {"_id": xyz},
              {"$set": {"name": a['name'],
                        "lastname": a.get('lastname', None)}})

This gives me None is lastname doesn't exist. I don't want lastname to be updated at all if there is not lastname in 'a'. Is there any other alternative apart from using 2 set statements?

Upvotes: 0

Views: 456

Answers (1)

Tomáš Linhart
Tomáš Linhart

Reputation: 10220

Prepare the update definition beforehand. For example, suppose a has this value:

a = {
    'name': 'John'
}

Then define the update so that it only contains fields from a that you are interested in (and that are present in a):

update = {
    'name': a.get('name'),
    'lastname': a.get('lastname')
    ...
}
update = {k: v for k, v in update.items() if v is not None}

Now perform the update:

b.update_one(
    {"_id": xyz},
    {"$set": update}
)

Upvotes: 1

Related Questions