如何在MongoDB 3.2文件中插入对象?

时间:2016-04-04 12:28:53

标签: java mongodb mongodb-java mongo-java-driver

我有User

public class User {
    private String name;
    private String email;

    public User () {  }

    public User(String name) {
        this.name = name;
    }

    public User(String name, String email) {
        this(name);
        this.email = email;
    }
    // getters and setters
}

我也有简单的POJO Comment

public class Comment {
    private String comment;
    private Date date;
    private String author;

    public Comment() { }

    public Comment(String comment, Date date, String author) {
        this.comment = comment;
        this.date = date;
        this.author = author;
    }
    // getters and setters
}

我想如何将新用户插入集合中,并对此发表一些评论:

public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("example");
    MongoCollection<Document> collection = db.getCollection("object_arrays");

    collection.drop();

    List<Comment> reviews = new ArrayList<Comment>(){{
        add(new Comment("cool guy", new Date(), "John Doe"));
        add(new Comment("best joker", new Date(), "Vas Negas"));
        add(new Comment("very stupid but very funny man", new Date(), "Bill Murphy"));
    }};
    Document user = new Document();
    user.append("user", new User("0xFF", "email@email.com"))
            .append("reviews", reviews)
            .append("createDate", new Date());
    collection.insertOne(user);
}

不幸的是,我有异常:

    Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.mongodb.course.com.mongodb.course.model.User.
    at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
    at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
    at org.bson.codecs.configuration.ChildCodecRegistry.get(ChildCodecRegistry.java:51)
    at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:174)
    at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:189)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:131)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:45)
    at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63)
    at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:29)
    at com.mongodb.connection.InsertCommandMessage.writeTheWrites(InsertCommandMessage.java:101)
    at com.mongodb.connection.InsertCommandMessage.writeTheWrites(InsertCommandMessage.java:43)
    at com.mongodb.connection.BaseWriteCommandMessage.encodeMessageBodyWithMetadata(BaseWriteCommandMessage.java:129)
    at com.mongodb.connection.RequestMessage.encodeWithMetadata(RequestMessage.java:160)
    at com.mongodb.connection.WriteCommandProtocol.sendMessage(WriteCommandProtocol.java:212)
    at com.mongodb.connection.WriteCommandProtocol.execute(WriteCommandProtocol.java:101)
    at com.mongodb.connection.InsertCommandProtocol.execute(InsertCommandProtocol.java:67)
    at com.mongodb.connection.InsertCommandProtocol.execute(InsertCommandProtocol.java:37)
    at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:159)
    at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:286)
    at com.mongodb.connection.DefaultServerConnection.insertCommand(DefaultServerConnection.java:115)
    at com.mongodb.operation.MixedBulkWriteOperation$Run$2.executeWriteCommandProtocol(MixedBulkWriteOperation.java:455)
    at com.mongodb.operation.MixedBulkWriteOperation$Run$RunExecutor.execute(MixedBulkWriteOperation.java:646)
    at com.mongodb.operation.MixedBulkWriteOperation$Run.execute(MixedBulkWriteOperation.java:401)
    at com.mongodb.operation.MixedBulkWriteOperation$1.call(MixedBulkWriteOperation.java:179)
    at com.mongodb.operation.MixedBulkWriteOperation$1.call(MixedBulkWriteOperation.java:168)
    at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:230)
    at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221)
    at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:168)
    at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:74)
    at com.mongodb.Mongo.execute(Mongo.java:781)
    at com.mongodb.Mongo$2.execute(Mongo.java:764)
    at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:515)
    at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:306)
    at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:297)
    at com.mongodb.course.week3.ArrayListWithObject.main(ArrayListWithObject.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

我知道MongoDB的Java驱动程序无法将我的对象转换为Document,并且它需要某种转换器。我也了解CodecCodecRegistryCodecProvider接口。顺便说一句,是否有更简单的方法将对象转换为mongo文档?你能举例说明我该怎么办? 谢谢。

2 个答案:

答案 0 :(得分:3)

您发布的代码的问题在于它默认不知道如何将您的pojo对象序列化为Json以将它们保存到数据库中。您可以使用MongoDB Java驱动程序执行此操作,但您需要做一些工作来序列化Comment ArrayList和User pojos。如果您添加一些杰克逊映射代码,您可以按如下方式执行此操作:

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.bson.Document;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Problem {
    public static void main(String[] args) {
        try (final MongoClient client = new MongoClient()) {
            final MongoDatabase db = client.getDatabase("example");
            final MongoCollection<Document> collection = db.getCollection("object_arrays");

            collection.drop();

            final List<Comment> reviews = new ArrayList<Comment>() {
                {
                    add(new Comment("cool guy", new Date(), "John Doe"));
                    add(new Comment("best joker", new Date(), "Vas Negas"));
                    add(new Comment("very stupid but very funny man", new Date(), "Bill Murphy"));
                }
            };

            final ObjectMapper mapper = new ObjectMapper();
            final User user = new User("0xFF", "email@email.com");
            try {
                //Create a Document representation of the User object
                final String userJson = mapper.writeValueAsString(user);
                final Document userDoc = Document.parse(userJson);

                //Convert the review ArrayList into a Mongo Document.  Need to amend this if not using Java8
                final List<Document> reviewDocs = reviews.stream().map(convertToJson())
                        .map(reviewJson -> Document.parse(reviewJson)).collect(Collectors.toList());

                //Wrap it all up to it can be saved to the database
                final Document wrapperDoc = new Document();
                wrapperDoc.append("user", userDoc).append("reviews", reviewDocs).append("createDate", new Date());
                collection.insertOne(wrapperDoc);
            } catch (final JsonProcessingException e) {
                e.printStackTrace();
            }
        }
    }

    private static Function<Comment, String> convertToJson() {
        final ObjectMapper mapper = new ObjectMapper();
        return review -> {
            try {
                return mapper.writeValueAsString(review);
            } catch (final JsonProcessingException e) {
                e.printStackTrace();
            }
            return "";
        };
    }
}

*这会使用一些您可能需要更改的Java8代码,具体取决于您使用的Java版本

正如关于这个问题的另一个答案所说,有一些框架可以将对象的序列化和与MongoDB的交互结合起来,这样你就不需要手动编写序列化代码了。例如,Spring有一个Mongo驱动程序,我使用了另一个名为Jongo的驱动程序,我发现它非常好。

答案 1 :(得分:1)

如果您想使用这样的Java对象,Morphia是您最好的选择。现在正在做的工作是支持像你一样尝试的任意Java类,但它还没有完成。