我有一个名为Status的Java类,它由3个字段组成,即:String Email,String Status,ArrayList(Comment)commentList。 Comment是另一个由2个String字段组成的Java类。我使用过MySQL,我知道如何将这个Status对象保存在数据库表中。现在我正在学习MongoDB,我需要将这个Status对象存储在我的db集合中。我该怎么做?截至目前,我已经尝试了以下内容并且无法存储Status对象。有人可以帮我吗? 我尝试过以下方法:
public static MongoClient getMongoConnection() {
MongoClient mongo = null;
try {
mongo = new MongoClient("localhost", 27017);
} catch (Exception e) {
e.printStackTrace();
}
return mongo;
}
public static void main(String[] args) {
MongoClient mongo = getMongoConnection();
DB db = mongo.getDB("myTestdatabase");
DBCollection myReviews = db.getCollection("myStatus");
BasicDBObject obj = new BasicDBObject();
List<Object> commentList = new BasicDBList();
commentList.add(new Comment("Looks like a nice status", "email@gmail.com"));
commentList.add(new Comment("This is a nice status", "email@gmail.com"));
Status status = new Status();
status.setStatus("This is my new Status");
status.setEmail("email@gmail.com");
obj.put("status", status.getStatus());
obj.put("email", status.getEmail());
obj.put("comments", commentList);
myReviews.insert(obj);
}
我收到此错误。
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.Comment.
答案 0 :(得分:0)
mongo.getDB已弃用。使用以下命令创建数据库。确保你也导入了bson。
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase db = mongo.getDatabase("myDB");
MongoCollection items = db.getCollection("myCollection");
Document document = new Document(); // Create the document to be inserted to the DB
document.put("First Name", "John");
document.put("Last Name", "Smith");
items.insertOne(document); // Insert document to DB