I'm using Spring Data with MongoDB and I'm having an issue accessing nested elements in my Mongo documents and convert those into Java fields. The following Spring query:
Query query = new Query().limit(1);
query.fields().include("a.d").exclude("_id");
mongoTemplate.find(query, MyObject.class);
returns the following DBObject:
{ "a" : { "d" : { "e" : 7.0 , "f" : 9.0}}}
I'm interested only in "e", and "f" so I decided to use a Converter<DBObject, MyObject>
. Here is the my converter function:
public MyObject convert(DBObject dbObject) {
DBObject dboA = (DBObject) dbObject.get("a");
DBObject dboD = (DBObject) dboA.get("d");
MyObject myObj = new MyObject();
myObj.setE((Double) dboD.get("e"));
myObj.setF((Double) dboD.get("f"));
return myObj;
}
Suppose that I have nested documents with a depth of 20/30, my converter would be way to painful to write. Is there a way to do this that is less clumsy and more elegant?
Is it possible to do this with annotations? Something like @Field(value = "a.d.e")
...
I feel like I'm missing something... Thanks!