我正在尝试将一个包含 JSONS 的 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),
Exception in thread "main" java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]
任何人都可以告诉我正确的方法吗?
Insert ArrayList mongodb 上面的问题是关于 JSONS 的批量插入,而不是单个插入。 我的问题很独特
最佳答案
异常提示了问题所在:列表不能用作记录(或类似 map 的数据结构)。
引用MongoDB documentation on documents组成一个集合:
Document Structure
MongoDB documents are composed of field-and-value pairs and have the following structure:
{ field1: value1, field2: value2, field3: value3, ... fieldN: valueN }
因此,在您的情况下,因为您只想在一次调用中插入许多文档,所以您需要做的是使用collection.insertMany
:
List<Document> documents = ...; //convert your list to a List<Document>
collection.insertMany(documents);
关于java - 在 Java 中将 ArrayList 插入到 mongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55932776/