Java:将json数组插入MongoDB时出错

时间:2018-03-01 23:42:46

标签: java json mongodb csv

我正在努力将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"
} ]

以下是我的代码: 第1步:将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");

        }
   }    

第3步:我的主要方法:

public class Main {

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

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

}

感谢任何帮助。感谢

1 个答案:

答案 0 :(得分: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");
   }
}