2

I want to update every field of my MongoDB collection using the field's own value to do so.

Example: if I have this document: "string": "foo", a possible update would do this: "string": $string.lower(). Here, $string would be "foo", but I don't know how to do this with PyMongo.

I've tried this:

user_collection.update_many({}, { "$set": { "word": my_func("$word")}})

Which replaces everything with "$word".

I've been able to do it successfully iterating each document but it takes too long.

2
  • From my understanding, you are reading the same document and updating the same document with different values for each keys. May be replace_one method will be more suitable for this. If you add some more details like how you are fetching the document and the update functions, will help to suggest better. Commented Jan 27, 2020 at 13:08
  • I want to update one field for each document in my collection. Yesterday I had to pass a urllib.parse function to decode a certain field for each document. Now I wanted the same thing using the .strip() method. In this case maybe it's doable with MongoDB's built-in $trim. Commented Jan 27, 2020 at 14:06

1 Answer 1

0

As I know you can't find and update in one statement using python function. You can either use mongo query language:

user_collection.update_many({}, { "$set": {"name": { "$concat": ["$name", "_2"]}}})

or use separate functions of pymongo:

for obj in user_collection.find({some query here}):
    user_collection.update({"_id": obj['_id']}, { "$set": {"name": my_func(obj['name']) } })
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.