I am trying to insert a whole Java object into a MongoDB Collection using Java. I am getting following error:
Error :
Exception in t
There have been several changes since this question was asked. Using test.java
in the question, here is what worked for me using Google's Gson
:
import com.google.gson.Gson;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class test {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient(); // Connect with default settings i.e. localhost:27017
MongoDatabase db = mongoClient.getDatabase("test"); // Get database "test". Creates one if it doesn't exist
Employee employee = new Employee(); // Create java object
employee.setNo(1L);
employee.setName("yogesh");
// Deserialize object to json string
Gson gson = new Gson();
String json = gson.toJson(employee);
// Parse to bson document and insert
Document doc = Document.parse(json);
db.getCollection("NameColl").insertOne(doc);
// Retrieve to ensure object was inserted
FindIterable iterable = db.getCollection("NameColl").find();
iterable.forEach(new Block() {
@Override
public void apply(final Document document) {
System.out.println(document); // See below to convert document back to Employee
}
});
}
}
You can also use Gson
to convert retrieved bson document back to Java object:
Gson gson = new Gson();
Employee emp = gson.fromJson(document.toJson(), Employee.class);