BasicBSONList can only work with number keys, not: [_id]

I am trying to insert multiple records into MongoDB at once, so for this I created a javaBean for each record to be inserted and added them to an ArrayList.

And finally, from ArrayList, I am trying to perform an insert operation as shown below

public void insert(ArrayList<QuoteReportBean> quotelist) { BasicDBList totalrecords = new BasicDBList(); StringBuffer sb = new StringBuffer(); int valuecount=0; for (QuoteReportBean reportbean: quotelist) { valuecount++; BasicDBObject dbrecord = new BasicDBObject(); dbrecord.append("cust_id", reportbean.getCustomerId()); dbrecord.append("unique_symbol", reportbean.getUniqueSymbol()); sb.append(reportbean.getUniqueSymbol()+","); dbrecord.append("exch", reportbean.getExchange()); dbrecord.append("access_time", reportbean.getDate()); totalrecords.add(dbrecord); } WriteResult result = coll.insert(totalrecords,WriteConcern.NORMAL); } 

But I am the next mistake

 Exception in thread "taskExecutor-1" java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id] at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:159) at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:150) at org.bson.types.BasicBSONList.get(BasicBSONList.java:104) at com.mongodb.DBCollection.apply(DBCollection.java:501) at com.mongodb.DBCollection.apply(DBCollection.java:491) at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:195) at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:180) at com.mongodb.DBCollection.insert(DBCollection.java:58) 

Can someone please help me how to solve this?

+4
source share
1 answer

BasicDBList cannot be used to insert multiple documents, it is used only for arrays within a single document. To do bulk insertion, you need to pass an array of DBObjects to the insert method.

I changed my code to do this and it worked without errors:

  StringBuffer sb = new StringBuffer(); int valuecount = 0; final QuoteReportBean[] quotelist = {new QuoteReportBean()}; DBObject[] totalrecords = new BasicDBObject[quotelist.length]; for (int i = 0; i < quotelist.length; i++) { QuoteReportBean reportbean = quotelist[i]; valuecount++; BasicDBObject dbrecord = new BasicDBObject(); dbrecord.append("cust_id", reportbean.getCustomerId()); dbrecord.append("unique_symbol", reportbean.getUniqueSymbol()); sb.append(reportbean.getUniqueSymbol() + ","); dbrecord.append("exch", reportbean.getExchange()); dbrecord.append("access_time", reportbean.getDate()); totalrecords[i] = dbrecord; } WriteResult result = coll.insert(totalrecords, WriteConcern.NORMAL); 
+3
source

Source: https://habr.com/ru/post/1496180/


All Articles