pymongo exception catching on unique index insert

103 views
Skip to first unread message

Raxit Sheth

unread,
Oct 10, 2012, 4:17:49 AM10/10/12
to mongod...@googlegroups.com
Hi

how to enable exception in pymongo? I am having unique index on some
field and if i am trying to insert duplicate entry on that index,
pymongo is silent, not throwing any exception.

Here is how i am testing, Sample code. steps to replicate ( > means
mongo console # means python code comment)

So either pymongo is not throwing exception [bug?] or i am not aware
how to catch exception

-----------------------------------
> use test
switched to db test
> db.test1.remove()
> db.test1.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "test.test1",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"b" : 1
},
"unique" : true,
"ns" : "test.test1",
"name" : "b_1"
}
]
> db.test1.insert({"b":"100"})
> db.test1.insert({"b":"100"})
E11000 duplicate key error index: test.test1.$b_1 dup key: { : "100" }
>


#---test1.py start-----
import pymongo
from pymongo import Connection
connection = Connection()
db = connection['test']
test1=db.test1
db.test1.insert({"b":"1"})
print "inserted"
db.test1.insert({"b":"1"})
print "inserted"
db.test1.insert({"b":"1"})
print "inserted"
#---test1.py end---------



> db.test1.find()
{ "_id" : ObjectId("50752da84bbac44e016aa9dc"), "b" : "100" }
{ "_id" : ObjectId("50752df78ef31a1e34000000"), "b" : "1" }

-------------------------------------



Thanks
Raxit

Raxit Sheth

unread,
Oct 10, 2012, 4:35:21 AM10/10/12
to mongod...@googlegroups.com
ok, safe=True is to enable, Thanks!
Reply all
Reply to author
Forward
0 new messages