How to convert a single BsonValue, such as "BsonArray" to json in the Java bson library

I am developing a function to import ChangStream into aws redshift. I need to convert the value of the composite field type (such as: BsonArray, BsonDocument) in mongodb into a JSON string.

The Java bson library can only convert BsonDocument to JSON string (using toJson method), but other composite field types such as BsonArray are not supported

For example, the following code

BsonArray bsonArray = new BsonArray();
bsonArray.add(new BsonString("apple"));
bsonArray.add(new BsonString("banana"));
bsonArray.add(new BsonString("orange"));

I want it to output as:


The driver does not provide this functionality but as a workaround, you could try something like:

    static String toJson(BsonArray bsonArray) {
        String jsonDocument = new BsonDocument("a", bsonArray).toJson();
        return jsonDocument.substring(jsonDocument.indexOf('['), jsonDocument.lastIndexOf(']') + 1).trim();