简体   繁体   中英

How to update MongoDB/PyMongo according to dictionary?

I'm looking to update all documents in a database for users such that each user gets an update similar to

for user in user_to_state:
  collection_users.update_one({"username":user}, {$set: {"state":user_to_state[user]}})

But I'd like to do it in a single query rather than iterating through the dictionary updating each one at a time. Is this possible? Is it faster than iterating?

If I have a dictionary of each user's username (a field currently on every document in this collection) and their state eg {"jim12":"TX", "jane34":"FL", ...} is there a way to do a singular query that submits the entire dictionary and goes through each or does it have to be iterated through with the update_one method?

Thanks in advance!

You should be able to use bulk write to do this.

queries = []
for user in user_to_state:
    query = {
        "updateOne": {
            "filter": {"username": user},
            "update": {"$set": {"state": user_to_state[user]}}
        }
    }
    queries.append(query)

collection_users.bulk_write(queries)

MongoDB docs here .

Pymongo docs here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM