javamongodbjacksonmongojack

Simple object insertion using MongoDB and MongoJack


I'm trying to follow the MongoJack tutorial but I'm failing the first task: Inserting an object into the database.

This is what I have:

DB db = new MongoClient().getDB("mydb");

JacksonDBCollection<MyDomainObject, String> coll =
    JacksonDBCollection.wrap(db.getCollection("coll"),
                             MyDomainObject.class,
                             String.class);

MyDomainObject obj = new MyDomainObject(ObjectId.get().toString(), 123456789L);

WriteResult<MyDomainObject, String> result = coll.insert(obj);

System.out.println(result.getSavedId());

Where MyDomainObject class looks as follows:

class MyDomainObject {

    // @org.mongojack.ObjectId  doesn't work
    public String id;
    public long someValue;

    public MyDomainObject(String id, long someValue) {
        this.id = id;
        this.someValue = someValue;
    }

}

With the above code I end up with the following exception:

Exception in thread "main" java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to java.lang.String
    at Test.main(Test.java:26)

And I can't for my life figure out why. Any help appreciated.


Solution

  • Apparently all I had to do was to rename

    public String id;
    

    to

    public String _id;
    

    (Annotating the field with @JsonProperty("_id") also seems to do the trick. AFAICT there's no way of saying that public String id should replace the _id field. If someone knows how to do this, I'm interested in how.