将CSV转JSON数组插入MongoDB时遇readStartDocument错误求助
Hey there, let's break down why you're hitting this error and how to fix it quickly.
What's Causing the Error?
The error message spells out the core issue: MongoDB's Java driver expects to receive individual BSON documents (not a top-level JSON array) when performing insert operations. Right now, you're passing the entire JSON array directly, so the driver tries to parse it as a single document and fails because it encounters an array instead of the expected document structure.
Step-by-Step Fix
Let's adjust your workflow to split that JSON array into individual documents before inserting:
1. Parse the JSON Array into a List of Documents
First, take your JSON array string (result) and convert it into a list of key-value maps (or POJOs if you have a defined schema for your data). Using Jackson, a common JSON library in Java, here's how you'd do it:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.util.Map; // ... your existing CSV-to-JSON code ... ObjectMapper objectMapper = new ObjectMapper(); // Convert the JSON array string to a list of individual document maps List<Map<String, Object>> documentList = objectMapper.readValue( result, new TypeReference<List<Map<String, Object>>>() {} );
2. Insert the List into MongoDB with insertMany
Next, convert these maps into MongoDB Document objects and use the insertMany method (built to handle multiple documents at once) instead of trying to insert the whole array:
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.stream.Collectors; // ... after connecting to your MongoDB database ... MongoCollection<Document> collection = yourDatabase.getCollection("your_target_collection"); // Convert the map list to MongoDB-compatible Document objects List<Document> mongoDocuments = documentList.stream() .map(Document::new) .collect(Collectors.toList()); // Insert all documents in one operation collection.insertMany(mongoDocuments);
Why This Works
insertManyis explicitly designed to accept a collection of individual documents, so it aligns perfectly with the structure of your parsed JSON data.- By breaking the top-level JSON array into separate entries, you're giving MongoDB exactly what it expects: discrete, valid documents.
Quick Pre-Check
Make sure your CSV-to-JSON conversion outputs a valid array of objects, like this:
[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
If your JSON has formatting issues (missing commas, mismatched brackets, etc.), that could cause additional parsing errors—so double-check that first if you run into trouble.
内容的提问来源于stack exchange,提问作者Rose

