0

I'm using Jongo with Play framework 2, java. I added some data into my MongoDB.

{"_id" : ObjectId("538dafffbf6b562617252178"), ... }

However, when I fetched the ObjectId from the database, it gave me like:

de.undercouch.bson4jackson.types.ObjectId@484431ff instead of 538dafffbf6b562617252178. I don't quite understand how can I get the ObjectId value. My class is defined as following:

public class Product {
    @JsonProperty("_id")
    protected String id;
    ...
    public Product() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

EDIT

In order to fetch the data, I simply use find() function provided by Jongo as following:

public static Iterable<Product> findAll(){
    return products().find().as(Product.class);
}
Christian P
  • 12,032
  • 6
  • 60
  • 71
lvarayut
  • 13,963
  • 17
  • 63
  • 87

2 Answers2

1

Your ObjectId is of type de.undercouch.bson4jackson.types.ObjectId. By looking at the source you can see that there isn't a toString method defined on that class, so the default toString implementation is used instead.

MongoDB's ObjectId is actually 12-bit BSON type that's constructed using:

a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.

The class your are using is built a little bit different - it's internally stored as 3 integers. It has public getTime, getMachine and getInc methods so you can create your own using those values. Something like this will probably get you what you want:

(id.getTime() + id.getMachine() + ide.GetInc()).toHexString()
Christian P
  • 12,032
  • 6
  • 60
  • 71
1

id field annotated with @JsonProperty("_id") just means that your product documents have custom ids (ie. setted by user eg: 1234, 5678, ...)

You should annotate id field with both @Id and @ObjectId annotations to tell Jongo to handle id field as a real ObjectId managed by MongoDB.

public class Product {

@org.jongo.marshall.jackson.oid.Id
@org.jongo.marshall.jackson.oid.ObjectId
protected String id;
...
  public Product() {
  }
}

During deserialization, a string representation of ObjectId will be setted into Product instances

Benoît Guérout
  • 1,977
  • 3
  • 21
  • 30
  • Thanks for your response. I tried what you mentioned above, however, it gave me `Execution exception[[RuntimeException: java.lang.IllegalArgumentException: invalid ObjectId [de.undercouch.bson4jackson.types.ObjectId@6e07e6fc] (through reference chain: java.util.ArrayList[0]->models.Product["_id"])]]` – lvarayut Jun 11 '14 at 11:34
  • You should open an issue https://github.com/bguerout/jongo/issues and provide the full stack trace. This question will be updated later with what we have found. – Benoît Guérout Jun 12 '14 at 19:00