Perhaps you are looking for Morphia , ORM for MongoDB for Java, afterall? For Morphia, this tutorial at Slideshare might be a good start.
Btw, I find the _id String username is better than contra Mongo ObjectId.
A small example:
//Routes GET /add/:username controllers.Application.createTestPerson(username) GET /delete/:username controllers.Application.delete(username) //Controller public class Application extends Controller { ... public static Result createTestPerson(String username){ //DB connection and Morphia Datastore DBConn conn = new DBConn("test"); Datastore ds = conn.getDatastore(); //Person document for saving Person person = new Person(username); person.setName("John", "Doe"); //save person to Mongo ds.save(person); return ok("user \""+username+"\" saved"); } public static Result delete(String username){ //DB connection and Morphia Datastore DBConn conn = new DBConn("test"); Datastore ds = conn.getDatastore(); ds.delete(Person.class,username); return ok("user \""+username+"\" deleted"); } } //models Person.java import com.google.code.morphia.annotations.*; import org.bson.types.ObjectId; @Entity("persons") public class Person { @Id String userName; Name name; public Person(String u){ userName = u; } public void setName(String first, String last){ name = new Name(first, last); } } @Embedded class Name { String first, last; public Name(){ } public Name(String first, String last) { this.first = first; this.last = last; } } //models DBConn.java import com.google.code.morphia.Datastore; import com.google.code.morphia.Morphia; import com.mongodb.Mongo; import java.net.UnknownHostException; public class DBConn implements AutoCloseable{ Morphia morphia; Mongo mongo; Datastore ds; public DBConn(){ new DBConn("test"); } public DBConn(String collection){ morphia = new Morphia(); try { mongo = new Mongo(); } catch (UnknownHostException ex) { System.out.println("[Error] MongoDB Error"); } ds = morphia.createDatastore(mongo, collection); System.out.println("DB conn success ["+ ds.getDB().getName() + "]"); } public Datastore getDatastore(){ return ds; } public void close() throws Exception { mongo.close(); } }
So,
localhost:9000/delete/what-ever-here localhost:9000/createTestPerson/what-ever-here
You can manage the Mongo collection and view the results in the Mongo console:
> db.persons.find() { "_id" : "johndoe", "className" : "models.Person", "name" : { "first" : "John", "last" : "Doe" } } >
source share