Hide
Hide

Reputation: 3317

pymongo insert only does not exist

I used InsertOne() for bulk insert.

user1 = InsertOne({"user_id": 1})
user2 = InsertOne({"user_id": 2})
collection.bulk_write([user1, user2])

If user_id = 1 already exist in collection, it throw batch op errors occurred errors.

I wonder that is there any method for only insert if data doesn't exist?

(Can't using get data and compare if data exist because I'm using bulk_write)

Upvotes: 2

Views: 198

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

What you can do is : Use ReplaceOne with upsert:true. So that if the document already exists update wont have any effect, and if it doesn't exist, it will create the new document.

Try this:

user1 = ReplaceOne({"user_id": 1},{"user_id": 1},upsert = True)
user2 = ReplaceOne({"user_id": 2},{"user_id": 2},upsert = True)
collection.bulk_write([user1, user2])

Make sure you pass all the data you need to store in the User document, in the second argument of ReplaceOne

Upvotes: 1

Related Questions