I am trying to insert a whole Java object into a MongoDB Collection using Java. I am getting following error:
Error :
Exception in t
DB db = mongoClient.getDB( "mydb" );
coll = db.getCollection("testCollection");
Employee emp = new Employee();
emp.setId("1001");
emp.setName("John Doe");
//Converting a custom Class(Employee) to BasicDBObject
Gson gson = new Gson();
BasicDBObject obj = (BasicDBObject)JSON.parse(gson.toJson(emp));
coll.insert(obj);
findEmployee(new BasicDBObject("id","1001"));
public static void findEmployee(BasicDBObject query){
DBCursor cursor = coll.find(query);
try {
while(cursor.hasNext()) {
DBObject dbobj = cursor.next();
//Converting BasicDBObject to a custom Class(Employee)
Employee emp = (new Gson()).fromJson(dbobj.toString(), Employee.class);
System.out.println(emp.getName());
}
} finally {
cursor.close();
}
}
I thought that it would be useful to post code that did conversions both ways.
Storing an Employee Object
Finding and re-creating an employee Object
Hope this is useful..