I\'m learning MongoDB with Java. I\'m trying to insert data to MongoDB with Java driver. I\'m doing inserting like in MongoDB tutorial and every thing is okey. But if I want
From the looks of what you are trying to do, you are trying to add some custom data type (in this case your POJO) but what you need to keep in mind is that fields in documents can only accept certain data types, not objects directly.
In case if you didn't know also, Mongo Documents are structured the same way as json. So you have to explicitaly create the documents by creating the fields and inserting the values into them. There are specific data types that are allowed in value fields:
http://mongodb.github.io/mongo-java-driver/3.0/bson/documents/
To help with your case, the code below takes your POJO as a parameter and knowing the structure of the POJO, returns a Mongo Document that can be inserted into your collection:
private Document pojoToDoc(Pojo pojo){
Document doc = new Document();
doc.put("Name",pojo.getName());
doc.put("Surname",pojo.getSurname());
doc.put("id",pojo.getId());
return doc;
}
This should work for insertion. If you want to index one of the fields:
database.getCollection("Records").createIndex(new Document("id", 1));
I hope this answers your question and works for you.