6

我在 MongoDB 的规范化数据模型结构中收到以下错误:

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

这是由这一行引起的:

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

具体toJson()部分。我的文档中有一个 DBRef 对象,因此我可以引用另一个集合中的文档。嵌入式文档结构不是选项。那么我该如何解决这个问题呢?

4

2 回答 2

6

您必须导入 DBRef 编解码器才能打印它,如果您希望它采用文档 json 样式,您需要为 DBRef 编写自己的编解码器并将其添加到您提供给 toJson() 的编解码器注册表中。

例如

CodecRegistry codecRegistry = MongoClientSettings.getDefaultCodecRegistry();
-------
final DocumentCodec codec = new DocumentCodec(codecRegistry, new BsonTypeClassMap());
-------
System.out.println(document.toJson(codec));
于 2015-08-06T09:51:38.830 回答
0

由于这是在谷歌中搜索错误时的第一个结果,并且接受的答案中的解决方案似乎并不那么简单,并且似乎不再有效,因为 MongoClient 不再有 getDefaultCodecRegistry() ,我将发布对我有帮助的内容:

    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()));

解决方案来自这里:https ://github.com/akitoshka/debezium/commit/8dd12d76acced74de7ab184bc18a4384565a70b7

于 2020-04-24T03:43:14.630 回答