有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个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
}

我还有简单的POJOComment

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) 个答案

  1. # 1 楼答案

    您发布的代码的问题是,默认情况下,它不知道如何将pojo对象序列化为Json以保存到数据库中。可以使用MongoDB Java驱动程序实现这一点,但需要做一些工作来序列化注释ArrayList和用户POJO。如果添加一些Jackson映射代码,可以按如下方式执行:

    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的驱动程序,我发现它非常好

  2. # 2 楼答案

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