java - 在 Java 中将 ArrayList 插入到 mongoDB

标签 java arrays json mongodb

我正在尝试将一个包含 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/

相关文章:

java - 如何下载 Maven jar

java - 在每个无状态 bean 方法之前执行一些逻辑

arrays - Powershell:从get-wmiobject win32_product过滤不需要的值

javascript - Jquery .ajax 获取 json 响应请求

javascript - JSON 数组 : OK Locally but get "Undefined" values when run from Server

Java Web应用程序: Monitoring Progress

java - 如何将要注入(inject)的当前 Activity 传递给 Dagger2 中的对象

PHP 多文本框数组

c++ - 如何编写最佳页面替换算法?

python - 使用 Python 打印并连接 Json 的元素