How can I write JSON to MongoDB with Java?

I’m using mongodb-driver-sync 4.2.3 with Java 8 and Jackson for handling JSON objects. Unfortunately, Jackson and MongoDB don’t seem to play well together, and I’m having to write my own codec for converting JsonNodes to/from Bson. I have custom classes with JsonNode properties, that I am trying to insert into MongoDB.

The issue I’m running into is that I can’t figure out how to write the JSON (either as a JsonNode or just a JSON String) to MongoDB in my codec.

     * Encode an instance of the type parameter {@code T} into a BSON value.
     * @param writer         the BSON writer to encode into
     * @param value          the value to encode
     * @param encoderContext the encoder context
    public void encode(BsonWriter writer, JsonNode value, EncoderContext encoderContext) {

This will write the JSON as a String, but I want it as an actual MongoDB Object, and not an escaped string. There does not appear to be an easy way to do this with BsonWriter. This seems like something pretty simple that shouldn’t be difficult. Any help would be appreciated; maybe I’m just approaching this wrong?

This is how my client is setup:

        MongoCredential credential = MongoCredential.createCredential(...);

        CodecRegistry pojoCodecRegistry = fromRegistries(
                        new JsonNodeCodecProvider(), // My custom codec

        MongoClientSettings settings = MongoClientSettings.builder()
                .applyToClusterSettings(builder ->
                        builder.hosts(Collections.singletonList(new ServerAddress(
                                // ...

        MongoClient client = MongoClients.create(settings);

I ended up creating POJO’s for each of my JSON properties, and their nested JSON… still think there should be an easier way to do this though, as POJO’s don’t always make sense

Have a look at the reference documentation for JsonObject, which allows you to read and write a JSON string directly from and to MongoDB.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.