Category Archives: Spring

Spring data mongo generates wrong query for geo query with $near

While working with Spring data mongo,  I had to search a collection using geo spatial query. I needed to find all items from a point within a radius.

Method in repository interface looks like:

Slice findByLocationNear(Point source, Distance distance, Pageable pageable);

Generated query filter is:

{ location: { $near: { x: 56.6474, y: 28.63752 }, $maxDistance: 0.01799856011519078 } }

But mongo expect longitude as the first property in $near query value, without considering property name(!).

And the query does not get expected result.

To solve the problem, right now I am using a way around. While constructing Point object, setting longitude first. Then the query returns expected result.

Point source = new Point(lng, lat);
repository.findByLocationNear(source, distance, pageable);