【问题标题】:Java: Error while inserting json array into MongoDBJava:将 json 数组插入 MongoDB 时出错
【发布时间】:2018-03-01 23:42:45
【问题描述】:

我正在将 CSV 文件插入 MongoDB。首先,我将我的 CSV 转换为 Json 格式的数组(参考:https://dzone.com/articles/how-to-convert-csv-to-json-in-java),然后尝试将其上传到 MongoDB,但面临以下错误(readStartDocument 只能在 CurrentBSONType 为 DOCUMENT 时调用,而不是当 CurrentBSONType 为 ARRAY 时调用.):

Exception in thread "main" org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is ARRAY.
    at org.bson.AbstractBsonReader.verifyBSONType(AbstractBsonReader.java:692)
    at org.bson.AbstractBsonReader.checkPreconditions(AbstractBsonReader.java:724)
    at org.bson.AbstractBsonReader.readStartDocument(AbstractBsonReader.java:452)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:148)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:45)
    at org.bson.Document.parse(Document.java:105)
    at org.bson.Document.parse(Document.java:90)
    at com.ucm.json.ConnectMongoDB.connectToMongoDB(ConnectMongoDB.java:52)
    at com.ucm.json.Main.main(Main.java:15)

我的 JSON 字符串(结果)如下所示:

[ {
  "query" : "ecn",
  "type" : "KeywordMatch",
  "url" : "http://insidedell.com/ecn",
  "description" : "ECN"
}, {
  "query" : "product marketing",
  "type" : "PhraseMatch",
  "url" : "http://dellemc.com/product",
  "description" : "Products"
}, {
  "query" : "jive",
  "type" : "ExactMatch",
  "url" : "http://test.com/jive",
  "description" : "Jive test"
} ]

以下是我的代码: 第一步:将CSV转成JSON格式字符串数组

public class CreateJSON {

    public String query;
    public String type;
    public String url;
    public String description; 
    String result ;
    public CreateJSON() {

    }
    public CreateJSON(String query,String type,String url,String description) {
        this.query = query;
        this.type = type;
        this.url = url;
        this.description = description;

    }

    public String createJsonFromCSV() throws IOException{
        String csvFile = "C:\\Projects\\frontKeymatch_default_frontend.csv";

        List<CreateJSON> createObjects = null;
        Pattern pattern = Pattern.compile(",");
        try (BufferedReader in = new BufferedReader(new FileReader(csvFile));){

            createObjects = in.lines().map(line ->{
                String[] x = pattern.split(line);
                return new CreateJSON(x[0],x[1],x[2],x[3]);

            }).collect(Collectors.toList());


             ObjectMapper mapper = new ObjectMapper();
             mapper.enable(SerializationFeature.INDENT_OUTPUT);
             result =  mapper.writeValueAsString(createObjects);

        } 
         return result;

    }
}

步骤 2) 连接到 MongoDB 并插入数据

public class ConnectMongoDB{
    public void connectToMongoDB(String resultFromCSV) throws JsonGenerationException, JsonMappingException, IOException {

    MongoClient mongo = new MongoClient( "localhost" ,27017);
    Document doc = Document.parse(resultFromCSV);

            mongo.getDatabase("db").getCollection("collection").insertOne(doc);

            System.out.println("success");

        }
   }    

第三步:我的主要方法:

public class Main {

    public static void main(String[] args) throws FileNotFoundException, IOException {

        CreateJSON upload = new CreateJSON();
        ConnectMongoDB mongo = new ConnectMongoDB();
        mongo.connectToMongoDB(upload.createJsonFromCSV());
    }

}

感谢任何帮助。谢谢

【问题讨论】:

  • 您是否尝试将整个 csv 文件作为单个数组文档插入到 mongodb 中? Document.parse 旨在处理单个文档而不是数组。
  • @Veeram 是的。这不是正确的做法吗?
  • 这取决于你想用它做什么。看看这个answer。它可能会帮助你。
  • @Veeram 基本上,我想将它存储在 MongoDB 集合中,然后稍后从另一个 java 应用程序访问该集合并获取特定查询的值,获取它的类型、url 和描述。
  • 好的,那么您应该将它们保存为单独的文档。

标签: java json mongodb csv


【解决方案1】:

没有从 json 数组到 Document 的直接转换。 Document.parse 适用于单个文档,是出错的原因。

您可以更新您的方法以删除中间的 CreateJSON 对象和 ObjectMapper,并直接将 csv 行映射到 Document 并将它们收集为 List。

将以下方法作为静态方法移动到主类,并使用 InsertMany 插入所有文档。

主要方法。

public class Main {

public static void main(String[] args) throws FileNotFoundException, IOException {
    ConnectMongoDB mongo = new ConnectMongoDB();
    mongo.connectToMongoDB(createJsonFromCSV());
}

public static List<Document> createJsonFromCSV() throws IOException {
    String csvFile = "C:\\Projects\\frontKeymatch_default_frontend.csv";
    List<Document> createObjects = null;
    Pattern pattern = Pattern.compile(",");
    try (BufferedReader in = new BufferedReader(new FileReader(csvFile));){
          createObjects = in.lines().map(line ->{
             String[] x = pattern.split(line);
             return new Document("query",x[0]).append("type", x[1]) //append other fields
          }).collect(Collectors.toList());
       }
     return createObjects;
    }
}

public class ConnectMongoDB{
    public void connectToMongoDB(List<Document> docs) throws IOException {
    MongoClient mongo = new MongoClient( "localhost" ,27017);
    mongo.getDatabase("db").getCollection("collection").insertMany(docs);
    System.out.println("success");
   }
}   

【讨论】:

  • 谢谢。我会试试这个,让你知道
  • 成功了。您的代码中有轻微的拼写错误。它应该是 insertMany 而不是 insertAll。非常感谢!!
【解决方案2】:

就我而言,我错过了 MongoRepository 中组管道周围的花括号,即我写了

@Aggregation(pipeline = {
        "$group: { _id: { $dateToString: { date: '$createdDate', format: '%Y-%m' } }, count: { $sum: 1 } }"
})
AggregationResults<SubmissionCount> getSubmissionsCountPerMonth();

而不是

@Aggregation(pipeline = {
        "{ $group: { _id: { $dateToString: { date: '$createdDate', format: '%Y-%m' } }, count: { $sum: 1 } } }"
})
AggregationResults<SubmissionCount> getSubmissionsCountPerMonth();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多