tindu edward
tindu edward

Reputation: 299

Spring data MongoDB sort spatial results

I am using Spring data MongoDB for my project.

This is my Java object

    @Document(collection="StoreData")
    public class StoreData{
         @Id
         private String id;
         private String storeName;
         private GeoJsonPoint storeLocation;
         private double geoLat;
         private double geoLng;
         private char isStoreOpenInd;
         private char doesStoreAcceptCreditInd;
   }

The front end makes a rest call to my backend application which queries this Mongo DB. On the request I will definitely get a geocode - lat and long. Apart from that I could also get a name or any of these indicators as well. The rest service is supposed to return results by applying all of these filter criteria BUT ALWAYS SORTED BY DISTANCE from the lat long provided in the request.

I was able to write a Query object with all these criteria and get the results using MongoTemplate. But the results are not sorted. How do i sort them?

This is my code till now.

    Query query = new Query();
    TextCriteria textCriteria =  TextCriteria.forDefaultLanguage().matchingAny(storeNameFromRequest);
    query.addCriteria(textCriteria);

    Point geoPoint = new Point(lngFromRequest, latFromRequest);
    Distance geoDistance = new Distance(10, "MI");
    Circle geoCircle = new Circle(geoPoint, geoDistance);
    query.addCriteria(Criteria.where("atmGeoLocation").withinSphere(geoCircle));

    query.addCriteria(Criteria.where("isStoreOpenInd").is(isStoreOpenIndFromRequest);

There is no place to add a SORT or ORDER BY. How do i get this?

Upvotes: 2

Views: 1054

Answers (1)

alexbt
alexbt

Reputation: 17085

You can specify a sort direction on the query:

query.with(new Sort(Sort.Direction.ASC, "field"));

EDIT after comments

As you mentioned in the comments, the answer above does not work for GeoPoint. You can find an alternative solution here: Spring mongoTemplate. Sort is not working in geo query (NearQuery)

This answer is a little dated, not sure if there's something new now (2016).

It uses $geoWithin and $centerSphere

Upvotes: 1

Related Questions