我试图一次向MongoDB插入多条记录,所以为此我为每个要插入的记录创建了一个javaBean并将它们添加到ArrayList。
最后从ArrayList,我正在尝试执行插入操作,如下所示
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);
}
但我是以下错误
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)
有人可以帮我解决这个问题吗?
答案 0 :(得分:3)
BasicDBList不能用于插入多个文档,它只用于单个文档中的数组。要进行批量插入,需要将DBObject数组传递给insert方法。
我更改了你的代码来执行此操作,并且它没有错误地工作:
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);