简体   繁体   English

如何根据字典更新MongoDB/PyMongo?

[英]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?如果我有每个用户的用户名的字典(该集合中每个文档当前的一个字段)和他们的 state 例如 {"jim12":"TX", "jane34":"FL", ...} 有没有办法做一个提交整个字典并遍历每个字典的单一查询,还是必须使用 update_one 方法对其进行迭代?

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 . MongoDB 文档在这里

Pymongo docs here . Pymongo 文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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