Python - Pymongo插入和更新文档

时间:2013-08-22 03:48:46

标签: python mongodb pymongo

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

示例:

在服务器数据库上:

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

发送到数据库:

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

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

collection.insert(myDict)

4 个答案:

答案 0 :(得分:19)

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

答案 1 :(得分:7)

您也可以使用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)

答案 2 :(得分:1)

对于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)

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

答案 3 :(得分:1)

您必须使用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) 

使用replace_one作为update方法is deprecated

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

如果要使用批量更新:

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)