4

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!

Marsellus Wallace
  • 17,991
  • 25
  • 90
  • 154
  • I might would take a look into simple json to Obj converter. See this question: http://stackoverflow.com/questions/13365218/accessing-nested-fields-in-mongodb-documents-using-spring-data-read-converters But the next Step would be a reduction of the nesting level, since 20 to 30 is a lot. – Marc Dec 04 '12 at 14:42
  • Oh, yes.. dammit sorry! look here: http://stackoverflow.com/questions/5015844/parsing-json-object-in-java and here: http://stackoverflow.com/questions/1395551/convert-a-json-string-to-object-in-java – Marc Dec 04 '12 at 15:23
  • I would strongly recommend never nesting objects to that many levels in Mongo - if you feel you need to do so, I would suggest that this is poor schema design. You will have difficulty querying and doing updates in multiple level embedded values. – Asya Kamsky Dec 12 '12 at 03:13
  • @AsyaKamsky Mongo themselves encourage nesting depending on the use case: http://docs.mongodb.org/ecosystem/use-cases/pre-aggregated-reports/ although I agree that 20/30 levels is excessive. – Jason Polites Nov 06 '13 at 23:28
  • Thank you, I'm familiar with that document. Note that examples all have levels of nesting that are 2/3 maximum, not 20 or 30 like you are asking about. – Asya Kamsky Nov 06 '13 at 23:29

0 Answers0