繁体   English   中英

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

[英]How to insert document with collection.update_many() into Collection (MongoDB) using Pymongo (No Duplicated)

我使用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} TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping 并且{db.collection_data.find({"postID": {"$in": i["postID"]}})}对吗?

您可以使用以下代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM