![](/img/trans.png)
[英]How to update a mongodb collection with single document using pymongo?
[英]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.