【问题标题】:How to insert document with collection.update_many() into Collection (MongoDB) using Pymongo (No Duplicated)如何使用 Pymongo 将带有 collection.update_many() 的文档插入到 Collection (MongoDB) 中(不重复)
【发布时间】:2019-03-26 11:49:35
【问题描述】:

我使用 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"]}})} 对吗?

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    您可以使用此代码:

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

    【讨论】:

    • 错误:SyntaxError: invalid syntax 其中upsert = True
    • { "upsert" :True } 可以解决该错误,因为第三个参数是对象类型。
    • 我试过你的解决方案,但我的错误没有解决(帖子中的同样错误)
    • db.collection_data.updateMany( {"postId": i["postID"]}, {"$set":i}, { upsert: True } )
    • 我试过这个代码,没有错误。请把你的新代码发给我。
    猜你喜欢
    • 2019-02-27
    • 2015-09-27
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    相关资源
    最近更新 更多