sanghmitra
sanghmitra

Reputation: 21

pymongo duplicate id error while running same code second time

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 }

Upvotes: 0

Views: 964

Answers (2)

hhharsha36
hhharsha36

Reputation: 3349

You can try to manually initialize and push the data along with ObjectId within python, every time you try to run the script.

from pymongo import MongoClient
from bson.objectid import ObjectId

#step 1: connection

client = MongoClient(port=27017)
db=client["book"]
collection = db["book_booklist"]

#step 2: create sample data
data= {'_id': ObjectId(), 'name':'Great ideas', 'price':'100', 'Author':'gogo','issue_duration':'30'}


value= collection.insert_one(data)
print(value)

Note: BSON module for python in auto-installed when you install pymongo package.

Upvotes: 1

kevinadi
kevinadi

Reputation: 13815

To elaborate on vikscool's comment:

>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> doc = {'x':1, 'y':1, 'z':1}
>>> print(doc)
{'x': 1, 'y': 1, 'z': 1}
>>> conn.test.test.insert_one(doc)
<pymongo.results.InsertOneResult object at 0x1075a2410>
>>> print(doc)
{'x': 1, 'y': 1, 'z': 1, '_id': ObjectId('5dcb4293a6d58c694795bc9d')}

Note that doc was mutated by the insert_one() method. It added the _id field, so when you try to insert it again, it will complain about duplicate _id.

Upvotes: 0

Related Questions