MongoDB 将文档转换为自定义类型

MongoDB casting documents into custom types

有没有什么方法可以从 MongoDB 值读取到我的类型的对象,而不用将它们从 SimpleDBObject 转换?

我试图从 coll.find() 集合中获取所有文档,但是当我遍历它们时,我得到

Can't find a codec for interface com.mynamespace.models.interfaces.Profile.

正确的做法是什么?我使用标准 Java 驱动程序。

据我所知,在 C# 和 Couchbase 中,我只是 writing/reading 将文档转换为我的自定义类型。这边怎么走?

我过去用过的东西是Mongo Jack。这提供了一个简单的包装器,根据他们的文档,它直接从 Mongo 流映射 POJO,而无需中介 SimpleDBObject。这也使用了Jackson库,所以你可以使用Jackson序列化和反序列化注释。

网站是这样说的:

Deserialises queried objects directly from the MongoDB stream, making it one of the (if not the) fastest object mappers for MongoDB out there.

也许这就是您要找的,是吗?

以下是网站上的示例:

JacksonDBCollection<MyObject, String> coll = JacksonDBCollection.wrap(dbCollection, MyObject.class,
        String.class);
MyObject myObject = ...
WriteResult<MyObject, String> result = coll.insert(myObject);
String id = result.getSavedId();
MyObject savedObject = coll.findOneById(id);

Codec infrastructure in the mongo-java-driver >= 3.0 pretty much does what you want. You do have to create the Codecs manually, but there have also been a few efforts to .

还有其他成熟的 ODM 框架,例如 Morphia 和 Spring Data MongoDB。

Morphia 是 MongoDB 和 Java 官方支持的 ODM。可以为您的 Java 对象编写自定义编解码器,以便序列化在很大程度上对您的应用程序透明。 Spring data 和 mongojack 也是不错的选择。 Spring-数据得到积极维护,但我不完全确定这些天 mongojack 的开发情况。