Python - Pymongo 插入和更新文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18371351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:35:18  来源:igfitidea点击:

Python - Pymongo Insert and Update Documents

pythonmongodbpymongo

提问by Dustin

Using PyMongo, I have a set of dict's in a list that I'd like to submit to my MongoDB. Some of the items in the list are new entries, and some are to update.

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

Example:

例子:

On Server Database:

在服务器数据库上:

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

To send to database:

发送到数据库:

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

I'm currently using the following to insert documents, but how would I do something like stated above? Any help is appreciated!

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

collection.insert(myDict)

采纳答案by Roman Pekar

Use upsertoption:

使用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)

回答by lovesh

You can also use save

您也可以使用保存

import pymongo
con = pymongo.MongoClient()
coll = con.db_name.collection_name

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

for doc in docs:
    coll.save(doc)

回答by TheMI

For pymongo 3.0 and later:

对于 pymongo 3.0 及更高版本:

import pymongo
con = pymongo.MongoClient()
collection = con.db_name.collection_name

docs = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
for d in docs:
    collection.update_many({'_id':d['_id']}, d,True)

Ref: http://api.mongodb.org/python/current/api/pymongo/collection.html

参考:http: //api.mongodb.org/python/current/api/pymongo/collection.html

回答by Sebastien DA ROCHA

You have to use the upsertto update (or insert) your data

您必须使用upsert来更新(或插入)您的数据

from pymongo import MongoClient
client = MongoClient()
collection = client.my_database.my_collection

objects = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
for obj in objects:
     collection.replace_one({"_id": obj["_id"]}, obj, upsert=True) 

Use replace_oneas the updatemethod is deprecated:

不推荐使用replace_oneupdate方法:

https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one

https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one

If you want to use bulk update:

如果要使用批量更新:

from pymongo import ReplaceOne

update_objects = list()
for obj in objects:
    update_objects.append(ReplaceOne( {'_id': obj['_id']},  obj, upsert=True))

collection.bulk_write(update_objects)