0

I am trying to import a json into MongoDB in a java program and I am getting the following exception. Exception in thread "main" org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is ARRAY

This is my source code.

    MongoClient client = new MongoClient("localhost", 27017);

MongoDatabase database = client.getDatabase("test2");

MongoCollection<Document> collection = 
          database.getCollection("collection1");

    int count = 0;
    int batch = 100;

    List<InsertOneModel<Document>> docs = new ArrayList<>();

    try(BufferedReader br = new BufferedReader(new FileReader("C:\\\\CsvFiles\\OneMillion.json"))) {
        String line;
        while((line = br.readLine()) != null) {
            docs.add(new InsertOneModel<>(Document.parse(line)));
            count++;
            if(count == batch) {
                collection.bulkWrite(docs, new BulkWriteOptions().ordered(false));
                docs.clear();
                count = 0;
            }
        }
    }
        if(count > 0) {
            collection.bulkWrite(docs, new BulkWriteOptions().ordered(false));
        }
}

Can you please let me know where I am going wrong?.

13
  • 1
    This answer will help you. As noted in the answer you've to parse the json entry as document by converting array into document. Commented Oct 22, 2018 at 13:35
  • 1
    yes that is correct. Json that you are trying to parse is an array and so you get the error. Convert into document in the java code as shown in the linked answer. Commented Oct 22, 2018 at 14:32
  • 1
    Your code posted in the question is almost right. Just replace docs.add(new InsertOneModel<>(Document.parse(line))); to Document document = Document.parse(String.format("{\"a\": %s}", line));docs.add(new InsertOneModel<>(document.get("a"))) Commented Oct 22, 2018 at 19:28
  • 1
    It appears you are converting the csv line into array of json values. You should convert into json document then your code should work as is. Commented Oct 22, 2018 at 20:12
  • 1
    Iterate over array and add it to insert model. replace docs.add(new InsertOneModel<>(document.get("a"))) with for(Document doc:document.get("a")) {docs.add(new InsertOneModel<>(doc));} Commented Oct 23, 2018 at 18:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.