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

问题描述 投票:0回答:1

我使用collection.update()将Document插入Collection中,因为每个数据都有不同的postID。我希望当我运行如果在MongoDB中插入帖子时,帖子将被更新(不会插入新帖子,postID首先与postID重叠)。这是我的数据结构:

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"]}})}是对的吗?

python mongodb pymongo
1个回答
1
投票

你可以使用这段代码:

db.collection_data.update_many(
    {"postId": i["postID"]},
    {"$set":i},
    upsert = True
)
© www.soinside.com 2019 - 2024. All rights reserved.