Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force property order in Spring Data MongoDB mapping

I have a Location object that I need to force the order of the properties when they get persisted to mongodb, but I'm not having much luck figuring out how to do it. The Location class looks something like:

Location {
   float lat;
   float lon;
   County county;
}

When it get's persisted into mongo, county is always before lat and lon. This is a problem because I'm trying to put a geoindex on it and the first two properties must be lat/long.

I have tried:

@XmlRootElement(name="location")
@XmlType(propOrder={"latitude", "longitude", "county"})
Location {
   float lat;
   float lon;
   County county;
}

That works when the location object is serialized to xml to my client, but not to the DB. It seems that spring data or some mongo mapper is always doing things in alphabetical order.

Does anyone know how to force the order properties get persisted into mongo? Thanks!

like image 598
Andrew Serff Avatar asked Jan 27 '26 12:01

Andrew Serff


1 Answers

You can use the @Field annotation's order attribute to force field order. So, if you have:

Location {
   @Field(order = 1)
   float lat;

   @Field(order = 2)
   float lon;

   @Field(order = 3)
   County county;
}

the fields are persisted in the following order: lat, lon, county.

like image 200
Kaitsu Avatar answered Jan 30 '26 02:01

Kaitsu