有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组在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的批量插入,而不是作为单个插入。 我的问题是独一无二的


共 (2) 个答案

  1. # 2 楼答案

    异常提示了问题所在:列表不能用作记录(或类似于地图的数据结构)

    要引用组成集合的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
    }
    

    因此,您需要做的是,在您的情况下,,因为您只想在一个调用中插入多个文档,使用^{

    List<Document> documents = ...; //convert your list to a List<Document>
    collection.insertMany(documents);