0
votes

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 }

2
As per 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 the null duplicate value MongoDB show duplicate key is null?vikscool

2 Answers

1
votes

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.

0
votes

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.