我使用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"]}})}
是对的吗?
你可以使用这段代码:
db.collection_data.update_many(
{"postId": i["postID"]},
{"$set":i},
upsert = True
)