Search code examples
mongodbmongodb-java

Maps/Collections in MongoDB Java driver


In the C# mongodb driver, there are 3 possible representations for Dictionaries: Document, ArrayOfArrays, ArrayOfDocuments. https://mongodb.github.io/mongo-csharp-driver/2.8/reference/bson/mapping/#dictionary-serialization-options

As far as I understand, the Java driver supports (only or by default) the "Document" representation.

Is there a Convention or other built-in way to configure the driver to use ArrayOfArrays? I was not able to see anything related in the MongoDB Java Driver documentation.


Solution

  • According to the Java driver team, the answer is that while there's isn't a simple flag:

    1. You can do it with a custom codec to handle Map conversions to a nested key, value array for all Maps.

    2. Alternatively, you could create a custom annotation could be used to set the codec for a single Class field in the POJO. That way you would not have to worry about all Maps being treated the same by the codec registry.

    If you want to store all maps in the same way, the first option is obviously easier. You can refer to the driver code to see how the built-in annotations are built.