I have a Spring Data MongoDB type containing a Set of Comparable types (DayOfWeek in my specific case). This is logically a set, an it is therefore represented as such in the object. Spring Data MongoDB saves the set to the database as a MongoDB array.
public class MyType {
private Set<DayOfWeek> daysOfWeek;
public Set<DayOfWeek> getDaysOfWeek() { return daysOfWeek; }
public void setDaysOfWeek(Set<DayOfWeek> d) { this.daysOfWeek = d; }
}
An array in MongoDB is an ordered data structure, but Java's Set is not. Therefore, when the Set is translated to the MongoDB type by Spring, an ordering is by necessity applied to the elements. The resulting array is in the Set's (generally arbitrary) iteration order, and not in a logical sorted order (or even in a guaranteed consistent order).
Using an arbitrary, inconsistent iteration order causes a number of (minor) issues. It makes the data more annoying to work with: it's harder to see what elements are present at a visual glance, and any tests on the database structure itself need to make sure they're ignoring the ordering of the resulting MongoDB array. It also means that the MongoDB field value could change over time despite it logically being the same value (and being the same value in the Java model), since the iteration order could vary each time the object is saved. Depending on how differences are determined, it could result in unnecessary updates to the database, since the array ordering may have changed even though nothing of any import has actually changed.
What I would like is the ability to use the natural order of the Set elements when saving the object to a MongoDB document. Ideally, I do not want to force the Java type to be a sorted set, since there is no logical reason it needs to be one, beyond wanting them saved in a predictable sorted order for convenience and consistency.
How can I ensure that my object containing an unordered Set is saved to MongoDB in a sorted order?