BasicBSONList只能使用数字键,而不能:[_id] [英] BasicBSONList can only work with numeric keys, not: [_id]
问题描述
我试图一次将多条记录插入到MongoDB中,为此,我为要插入的每条记录创建了一个JavaBean并将它们添加到ArrayList中.
I am trying to insert multiple records to MongoDB at once , so for this i created a javaBean for each record to be inserted and added them to ArrayList .
最后从ArrayList中,我尝试执行如下所示的插入操作
And finally from the ArrayList , i am trying to perform a 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);
}
但是我是以下错误
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)
有人可以帮助我解决此问题吗?
推荐答案
BasicDBList不能用于插入多个文档,它仅用于单个文档中的数组.要进行批量插入,您需要将DBObjects数组传递给insert方法.
BasicDBList can't be used to do inserts of multiple documents, it's only used for arrays inside a single document. To do a bulk insert, you need to pass an array of DBObjects into the insert method instead.
我更改了您的代码以执行此操作,并且它的工作没有错误:
I changed your code to do this, and it worked without error:
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);
这篇关于BasicBSONList只能使用数字键,而不能:[_id]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!