获得“错误” :使用Java驱动程序插入mongo时出现E11000重复键错误 [英] Getting "err" : "E11000 duplicate key error when inserting into mongo using the Java driver

查看:126
本文介绍了获得“错误” :使用Java驱动程序插入mongo时出现E11000重复键错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


线程main中的异常com.mongodb.MongoException $ DuplicateKey:{
serverUsed:localhost / 127.0.0.1:27017,err:E11000重复
键错误索引:twitterdb03.LevelAFollowers。$ id dup key:{:
ObjectId('52d5636de408652b4853a8fe')},code:11000,n:0 ,
connectionId:12,ok:1.0}

Exception in thread "main" com.mongodb.MongoException$DuplicateKey: { "serverUsed" : "localhost/127.0.0.1:27017" , "err" : "E11000 duplicate key error index: twitterdb03.LevelAFollowers.$id dup key: { : ObjectId('52d5636de408652b4853a8fe') }" , "code" : 11000 , "n" : 0 , "connectionId" : 12 , "ok" : 1.0}

我正在使用mongo 2.11.1

I'm using mongo 2.11.1

java中的简单写入操作从未出现过问题

Never had problems with simple write operations in java

myMap.put(inid, followersList);
myObj.putAll(myMap);
myIdMapCollection.insert(myObj);


推荐答案

我找到了答案此页。我猜你的代码看起来像这样(大大简化了)?:

I found an answer on this page. I’m guessing your code looks something like this (greatly simplified)?:

doc = {} 
for i in xrange(2): 
    doc['i'] = i 
    collection.insert(doc) 

问题是,在插入之前,PyMongo会在文档中注入_id字段,如果 _id 字段不存在它( _id 总是使用10gen驱动程序生成客户端)。这意味着第一次通过循环 _id 由insert方法添加。由于 doc 是在循环外定义的,因此每次后续循环都会使用相同的 _id

The problem is that PyMongo injects an _id field into the document, if the _id field does not exist, before inserting it (_id is always generated client side with 10gen drivers). That means that the first time through the loop _id is added by the insert method. Since doc is defined outside the loop, each subsequent pass through the loop uses the same value for _id.

解决方案:


  1. 删除密钥_id




for i in xrange(2): 
    doc['i'] = i 
    if '_id' in doc: 
        del doc['_id'] 
    collection.insert(doc)





  1. 或手动创建一个新的:




from bson.objectid import ObjectId 
for i in xrange(2): 
    doc['i'] = i 
    doc['_id'] = ObjectId() 
    collection.insert(doc)


这篇关于获得“错误” :使用Java驱动程序插入mongo时出现E11000重复键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆