[英]how to insert object in mongodb
我的课如下:
package mongo;
import com.mongodb.BasicDBObject;
public class tweet extends BasicDBObject{
private String name;
private Integer id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
现在,我试图将此类的对象插入mongodb中:
public void connect() throws UnknownHostException
{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "test" );
tweet t=new tweet();
t.setId(100);
t.setName("Gggggg");
DBCollection Collection = null ;
Collection = db.getCollection("test");
DBObject doc = new BasicDBObject();
doc.put("first", t);
Collection.save( doc);
System.err.println(Collection.findOne());
}
但是,当我运行此代码时,对象t未插入数据库,并且system.err.println
返回以下内容:
{ "_id" : { "$oid" : "546c00efbadcd42088c8fee3"}}
如何将对象添加到mongodb中? 有可能这样做吗?
BasicDBObject
实际上是一个LinkedHashMap
。 因此,在扩展它时,需要像在map
一样put
和retrieve
值。
因此,简单地将值设置为属性是没有意义的,这些属性需要放在Tweet
映射中。
您需要按如下所示修改您的Tweet
类:
class Tweet extends BasicDBObject{
public String getName() {
return (String)this.get("name");
}
public void setName(String name) {
this.put("name", name);
}
public Integer getId() {
return (Integer)this.get("_id");
}
public void setId(Integer id) {
this.put("_id", id);
}
}
和您的主要方法是:
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "test" );
Tweet t=new Tweet();
t.setId(100);
t.setName("Ghorbani");
DBCollection collection = null ;
collection = db.getCollection("test");
collection.save(t);
System.err.println(collection.findOne());
如果您注意到, collection.save(t);
, Tweet
对象将被直接保存。 这就是它应该如何工作的。
O / P:
{ "_id" : 100 , "name" : "Ghorbani"}
您似乎正在尝试为对象设置ID。 通常,这是Mongo自动完成的。 尝试删除t.setId(100);
然后再次运行您的代码。
提示-尝试使用Mongoose管理与Mongo的连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.