簡體   English   中英

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

[英]How to insert object in MongoDB 3.2 document?

我有一個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文檔? 您能舉例說明我該怎么做嗎? 謝謝。

您發布的代碼的問題在於,默認情況下它不知道如何將pojo對象序列化為Json並將其保存到數據庫中。 您可以使用MongoDB Java驅動程序執行此操作,但是需要做一些工作來序列化Comment ArrayList和User pojos。 如果添加一些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版本來進行更改

正如關於這個問題的另一個答案所說,那里有可以結合使用Objects的序列化和與MongoDB交互的框架,因此您不需要手工編寫序列化代碼。 例如,Spring有一個Mongo驅動程序,而我使用了另一個名為Jongo的驅動程序,我發現它相當不錯。

如果您想使用這樣的Java對象, Morphia是您的最佳選擇。 現在正在完成支持任意Java類的工作,就像您正在嘗試的那樣,但尚未完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM