If I have MongoDB documents with both _id & id fields how do I convert those to POJO using PojoCodecProvider?
I have tried:
PojoCodecProvider.Builder pojoCodecProviderBuilder = PojoCodecProvider.builder()
.automatic(true)
.conventions(asList(org.bson.codecs.pojo.Conventions.ANNOTATION_CONVENTION));
With POJO annotated as:
public class MyModel {
@BsonProperty("_id")
public ObjectId _id;
@BsonProperty("id")
private String id;
@BsonProperty("id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
...
}
However the _id is null, only the id and other fields are set. I need all fields including the _id field to be set. How can I do this?
Thanks,
David
Aasawari
(Aasawari Sahasrabuddhe)
#3
Hi @David_Hoffer and welcome to the MongoDB Community forum!!
Here is how my POJO class looks like to insert _id and id together:
public class Test {
@BsonProperty("_id")
public ObjectId _id;
@BsonProperty("id")
private String id;
public Test(ObjectId objectId, String testing2) {
this._id= objectId;
this.id = testing2;
}
@Override
public String toString(){
return "Details ['_id= + _id +, id=' + id ']";
}
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
And the codec that I have been using looks like the following:
public static void main(String[] args) {
CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
I tried to create one constructor and insert _id and id together into the document.
Let me know if this answers your question.
Best regards
Aasawari