重复ID创建错误Mongodb

时间:2014-04-18 10:58:52

标签: mongodb exception on-duplicate-key

我正在使用pentaho数据集成工具从SQL Server数据库填充Mongodb集合。 mongodb集合中没有定义索引。由于在集合中创建了重复的ID,作业失败了。

我想知道它可能导致问题的情况。任何建议都会非常有用。

occurred during write: com.mongodb.MongoException$Network: Write operation to server /myhost:27017 failed on database transactions

    ERROR (version 5.0.1-stable, build 1 from 2013-11-15_16-08-58 by buildguy) : An error     occurred during write: com.mongodb.MongoException$DuplicateKey:
   { "serverUsed" : "/myhost:27017" , "connectionId" : 186 , "err" :
   "insertDocument :: caused by :: 11000 E11000 duplicate key error
   index: transactions.datacollection.$_id_  dup key: { :
   ObjectId('534fe5644503839b0f6d47a2') }" , "code" : 11000 , "n" : 0 ,
   "ok" : 1.0} 

ERROR (version 5.0.1-stable, build 1 from 2013-11-15_16-08-58 by buildguy)
   : An error occurred during write:
   com.mongodb.MongoException$DuplicateKey: { "serverUsed" :
   "/myhost:27017" , "connectionId" : 186 , "err" : "insertDocument ::
   caused by :: 11000 E11000 duplicate key error index:
   transactions.datacollection.$_id_  dup key: { :
   ObjectId('534fe5644503839b0f6d47a2') }" , "code" : 11000 , "n" : 0 ,
   "ok" : 1.0}  

   ERROR (version 5.0.1-stable, build 1 from 2013-11-15_16-08-58 by buildguy)
   : An error occurred during write: com.mongodb.MongoException$Network:
   Write operation to server /myhost:27017 failed on database
   transactions

   MongoDB Output.0 - ERROR (version 5.0.1-stable, build 1 from
   2013-11-15_16-08-58 by buildguy) : An error occurred during write:
   com.mongodb.MongoException$DuplicateKey: { "serverUsed" :
   "/myhost:27017" , "connectionId" : 187 , "err" : "insertDocument ::
   caused by :: 11000 E11000 duplicate key error index:
   transactions.datacollection.$_id_  dup key: { :
   ObjectId('534fe5644503839b0f6d47a2') }" , "code" : 11000 , "n" : 0 ,
   "ok" : 1.0}

   ERROR (version 5.0.1-stable, build 1 from 2013-11-15_16-08-58 by buildguy) : Unexpected   error ERROR (version 5.0.1-stable, build 1 from
   2013-11-15_16-08-58 by buildguy) :

2 个答案:

答案 0 :(得分:0)

默认情况下,如果您没有提供,则由mongodb(驱动程序或守护程序)自动添加_id fied。 _id使用唯一属性编制索引。见http://docs.mongodb.org/manual/reference/method/db.collection.insert/

如果驱动程序正在处理java驱动程序所做的事情(至少对于最新版本),并且您执行以下操作

    MongoClient c =  new MongoClient(new MongoClientURI("mongodb://somehost"));
    DB db = c.getDB("someDB");
    DBCollection coll = db.getCollection("someCollection");
    BasicDBObject obj = new BasicDBObject("field1", "value1");

    coll.insert(obj);

    obj.removeField("field1");
    obj.append("field1", "value2");
    coll.insert(obj);
    //maybe in a loop

您遇到了麻烦,因为第一次调用insert时,不会生成_id,以后也无需重新生成它。你一直在使用相同的_id。您可以创建一个新的basicDBObject来删除字段_id来解决问题。

答案 1 :(得分:0)

对于生成随机数据并插入MongoDB的模拟应用程序,我遇到了同样的问题,如果这有用的话。每次调用BasicDBObject的插入操作时,在函数末尾都会调用“clear()”操作。