gpt4 book ai didi

Python - Pymongo 插入和更新文档

转载 作者:IT老高 更新时间:2023-10-28 13:09:48 38 4
gpt4 key购买 nike

使用 PyMongo,我在一个列表中有一组字典,我想提交给我的 MongoDB。列表中有些项目是新条目,有些是要更新的。

例子:

在服务器数据库上:

[{"_id" : 1, "foo" : "bar}]

发送到数据库:

[{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]

我目前正在使用以下方法插入文档,但我将如何执行上述操作?任何帮助表示赞赏!

collection.insert(myDict)

最佳答案

使用 upsert选项:

from pymongo import MongoClient
cl = MongoClient()
coll = cl["local"]["test2"]

data = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
for d in data:
coll.update({'_id':d['_id']}, d, True)

关于Python - Pymongo 插入和更新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18371351/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com