0

I insert data to document using pymongo :

client = MongoClient()
db = client['comment_data2']
collection_data = db['comments']
collection_data.insert_many(data_comment)

Each data I have an "postid" to distinguish, like:

comment1 = {
        'commentParentId': parent_content.text,
        'parentId': parent_ID,
        'posted': child_time.text,
        'postID':child_ID,
        'author':
              {
                'name': child_name.text
              },
        'content': child_content.text
 }

I run my code more than 2 times and I see my data with duplicates. I want to when I run my code, each postID juch insert 1 times. I'm processing learn pymongo so I don't have any idea for solution. I find a solution in another post on StackOverFlow:

get_db().users.update(
     {'_id':ObjectId(session['user_id'])},
     {
         '$addToSet':{
                 'hme':ObjectId(id)
         }
     },
     upsert=True
)

But I dont know what does it mean. Source : https://stackoverflow.com/questions/31043412/insert-not-duplicate-data-with-pymongo-in-mongodb

UPDATE1 : I have tried to use collection_data.update_many(data_comment, upsert=True), but appear an Error : update_many() missing 1 required positional argument: 'update'

  • An ["upsert"](https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-option) is a special function of *update* commands in MongoDB, which alters the behavior of a normal update to not just *modify* but to instead **insert** only when the criteria provided *does not match* any existing document. This can be used so that when an "existing document to the conditions" ( duplicate ) is found, it only attempts updates, and only "inserts" when nothing exists. Alternately, you can specifically trap duplicate key errors. But you also need indexes to enforce that. – Neil Lunn Mar 26 '19 at 10:16
  • I have tried to use : `collection_data.update_many(data_comment, upsert=True)`, but appear Error : `collection_data.update_many(data_comment, upsert=True)` – Toan Nguyen Phuoc Mar 26 '19 at 10:47

0 Answers0