I am trying to insert a whole Java object into a MongoDB Collection using Java. I am getting following error:
Error :
Exception in t
Use BasicDBObjectBuilder to convert your POJO to an instance of DBObject which a DBCollection can save:
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
public class Employee {
private long no;
private String name;
// Getters and Setters
public DBObject toDBObject() {
BasicDBObjectBuilder builder = BasicDBObjectBuilder
.start("no", no)
.append("name", name);
return builder.get();
}
}
In order to save, just call toDBObject()
on POJO instance and provide it to collection:
public class test {
public static void main(String[] args) throws UnknownHostException,
MongoException {
...
DBCollection dbCollection = db.getCollection("NameColl");
Employee employee = new Employee();
employee.setNo(1L);
employee.setName("yogesh");
dbCollection.save(employee.toDBObject());
}
}
Using this approach:
DBObject
every time