Search code examples
javamongodbmorphia

Declaratively wrap array elements with objects in MongoDB/Morphia


I have a legacy DB structure, where every array element is wrapped as a key-value:

"field" : [
  {
    "_id" : ObjectId("123456789012345678901234")
  }, {
    "_id" : ObjectId("123456789012345678901235")
  }
]

Can I model it in Java without introducing an intermediate object? E.g. something like

@SomeMagicAnnotation("_id")
List<ObjectId> field;

Solution

  • Morphia will want a class structure to map because of those documents. You can, however, use @PostLoad to iterate over that array and create a new array with only those ObjectId values. Once you have this new array, you can put it back in the DBObject with put("field", newArray). This will make it look like a bare array of ObjectID values to Morphia who can then map it to your List<ObjectID>.