gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:16:41 27 4
gpt4 key购买 nike

我正在努力将 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");

}
}

第三步:我的主要方法:

public class Main {

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

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

}

感谢任何帮助。谢谢

最佳答案

没有从 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");
}
}

关于Java:将 json 数组插入 MongoDB 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49060563/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com