如何使用Pymongo将具有collection.update_many()的文档插入Collection(MongoDB)中(不重复)

时间:2019-03-26 11:49:35

标签: python mongodb pymongo

我使用collection.update()将Document插入Collection中,因为每个数据我都有一个postID不同。我想在运行时(如果在MongoDB中插入了帖子)将对帖子进行更新(不先插入postIDpostID重叠的新帖子)。这是我的数据的结构:

comment1 = [
   {
     'commentParentId': parent_content.text,
     'parentId': parent_ID,
     'posted': child_time.text,
     'postID':child_ID,
     'author':
          {
           'name': child_name.text
          },
     'content': child_content.text
   },
   ...............
]

这是我的代码,我曾经插入数据:

client = MongoClient()
db = client['comment_data2']
db.collection_data = db['comments']
for i in data_comment:
   db.collection_data.update_many(
        {db.collection_data.find({"postID": {"$in": i["postID"]}})},
        {"$set": i},
        {'upsert': True}
   )

但是我在第TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping行有一个错误:{'upsert': True}{db.collection_data.find({"postID": {"$in": i["postID"]}})}对吗?

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

db.collection_data.update_many(
    {"postId": i["postID"]},
    {"$set":i},
    upsert = True
)
相关问题