Georgi
Georgi

Reputation: 251

Resolve DBRef into Json

I'm getting the following error in a Normalized Data Model structure in MongoDB:

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.mongodb.DBRef

It's caused by this line:

System.out.println(document.toJson());

Specifically the toJson() part. I have a DBRef Object in my Document, so I can reference a Document from another Collection. An Embedded Document Structure is not option. So how can I fix this?

Upvotes: 8

Views: 3612

Answers (2)

Georgi
Georgi

Reputation: 251

You have to import the DBRef Codec for it to print it, if u want it in a document json style you need to write your own Codec for DBRef and add it to the codecregistry you give toJson().

e.g.

CodecRegistry codecRegistry = MongoClientSettings.getDefaultCodecRegistry();
-------
final DocumentCodec codec = new DocumentCodec(codecRegistry, new BsonTypeClassMap());
-------
System.out.println(document.toJson(codec));

Upvotes: 7

jad
jad

Reputation: 63

Since this is the first result when searching for the error in google and the solution in the accepted answer doesn't seem that straightforward and no longer seems to work since MongoClient does not have a getDefaultCodecRegistry() any longer, I will post what helped me:

    protected MongoCollection<Document> collection;

      private final CodecRegistry DEFAULT_REGISTRY = CodecRegistries.fromProviders(
          asList(new ValueCodecProvider(),
              new BsonValueCodecProvider(),
              new DocumentCodecProvider(),
              new DBRefCodecProvider(),
              new DBObjectCodecProvider(),
              new BsonValueCodecProvider(),
              new GeoJsonCodecProvider(),
              new GridFSFileCodecProvider()));

      private final BsonTypeClassMap DEFAULT_BSON_TYPE_CLASS_MAP = new BsonTypeClassMap();

      private final DocumentCodec documentCodec = new DocumentCodec(
          DEFAULT_REGISTRY,
          DEFAULT_BSON_TYPE_CLASS_MAP
      );
-----------------------------------------------------------------------
JsonWriterSettings writerSettings = org.bson.json.JsonWriterSettings.
        builder().
        outputMode(JsonMode.SHELL).
        indent(true)
        .build();

    JsonArray jsonArray = new JsonArray();
    collection.
        find().
        iterator().
        forEachRemaining(entry -> jsonArray.add(new JsonParser().parse(entry.toJson(writerSettings, documentCodec)).getAsJsonObject()));

The solution comes from here: https://github.com/akitoshka/debezium/commit/8dd12d76acced74de7ab184bc18a4384565a70b7

Upvotes: 0

Related Questions