mongodb-java POJO not returning id

Viewed 679

I'm new to MongoDB and getting a bit crazy here. I'm using the latest mongo-java-driver version and dropwizard.

I use POJO to write to the DDBB, which works. However, when trying to get the element, I don't get the actual _id. Here is what I tried:

DDBB document

{
   _id:603c249cbb33487d9baa49f8,
   name:"John"
}

Person Class

public class Person {

    @BsonProperty("_id")
    @BsonId
    private ObjectId id;

    @NotNull
    @JsonProperty
    private String name;

}

Returns:

{
    "id": {
        "timestamp": 1614554268,
        "counter": 11160056,
        "machineIdentifier": 12268360,
        "processIdentifier": 32155,
        "timeSecond": 1614554268,
        "time": 1614554268000,
        "date": 1614554268000
    },
    "name": "John"
}

As you can see, it doesn't return the actual _id (eg 603c249cbb33487d9baa49f8). I've tried making id a String, but I get the error Failed to decode 'Person'. Decoding '_id' errored with: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is OBJECT_ID.

I followed several guides and I've searched questions here, but nothing seems to work.

Any help is much appreciated!

2 Answers

You don't need to use @BsonId, you can simply use @Id and data-type of id field should be String. In this case, you will get 12bit Id generated by mongo.

public class Person {

    @Id
    private String id;

    @NotNull
    @JsonProperty
    private String name;

}

You can just use @MongoId instead of @BsonId

public class Person {

    @MongoId
    private String id;

    @NotNull
    @JsonProperty
    private String name;

}
Related