0

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?

1 Answer 1

1

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}
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.