Reputation: 306
I insert Document into Collection with collection.update() because each data I have a postID
to different. I want to when I run if a post was inserted in MongoDB, the post will be updated (not insert a new post with postID
overlapping with postID
first). This is a structure of my data:
comment1 = [
{
'commentParentId': parent_content.text,
'parentId': parent_ID,
'posted': child_time.text,
'postID':child_ID,
'author':
{
'name': child_name.text
},
'content': child_content.text
},
...............
]
This is my code, i used to insert data :
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}
)
But I have a Error : TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping
in line {'upsert': True}
. And {db.collection_data.find({"postID": {"$in": i["postID"]}})}
is right?
Upvotes: 0
Views: 641
Reputation: 4392
you can use this code:
db.collection_data.update_many(
{"postId": i["postID"]},
{"$set":i},
upsert = True
)
Upvotes: 1