I'm trying pymongo first time, when I try to insert data in the collection, at first it is successfully created but when I run same script it throws id duplication error. I read that mongodb/pymongo itself creates unique id if we don't mention it. I want to use auto-generation of id method which seems simple and good for heavy database(isn't it?). how to do that?
from pymongo import MongoClient
#step 1: connection
client = MongoClient(port=27017)
db=client["book"]
collection = db["book_booklist"]
#step 2: create sample data
data= {'name':'Great ideas', 'price':'100', 'Author':'gogo','issue_duration':'30'}
value= collection.insert_one(data)
print(value)
Error: on second try pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: book.book_booklist index: primary_key dup key: { id: null }
pymongo
what happens at every insert operation is that it appends a special key_id
to the original object reference at:Insert Document. So, it would be better to clear the_id
key's value(if you are trying to re-insert the same document). More on thenull
duplicate value MongoDB show duplicate key is null? – vikscool