数组在Java中向mongoDB插入ArrayList
我正试图将一个包含JSON的ArrayList插入到mongodb集合中
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("structure");
DBCollection collection = db.getCollection("chapter");
List<Document> data = new ArrayList<>();
collection.insertMany(data);
String str = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"}]";
DBObject dbObject = (DBObject) JSON.parse(str);
collection.insert(dbObject);
但我有个例外
Exception in thread "main" java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]
有人能告诉我正确的方法吗
Insert ArrayList mongodb 上面的问题是关于JSON的批量插入,而不是作为单个插入。 我的问题是独一无二的
# 1 楼答案
看看这个
https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/
# 2 楼答案
异常提示了问题所在:列表不能用作记录(或类似于地图的数据结构)
要引用组成集合的MongoDB documentation on documents,请执行以下操作:
因此,您需要做的是,在您的情况下,,因为您只想在一个调用中插入多个文档,使用^{: