java.lang.Object
org.springframework.data.mongodb.core.query.NearQuery
- All Implemented Interfaces:
ReadConcernAware,ReadPreferenceAware
Builder class to build near-queries.
MongoDB
Please note that there is a huge difference in the distance calculation. Using the legacy format (for near) operates upon Radians on an Earth like sphere, whereas the GeoJSON format uses Meters. The actual type within the document is of no concern at this point.
To avoid a serious headache make sure to set the
In other words:
Assume you've got 5 Documents like the ones below
Still as we've been requesting the
MongoDB
$geoNear operator allows usage of a GeoJSON Point or legacy coordinate pair. Though
syntactically different, there's no difference between near: [-73.99171, 40.738868] and near: { type:
"Point", coordinates: [-73.99171, 40.738868] } for the MongoDB serverPlease note that there is a huge difference in the distance calculation. Using the legacy format (for near) operates upon Radians on an Earth like sphere, whereas the GeoJSON format uses Meters. The actual type within the document is of no concern at this point.
To avoid a serious headache make sure to set the
Metric to the desired unit of measure which ensures the
distance to be calculated correctly.In other words:
Assume you've got 5 Documents like the ones below
{
"_id" : ObjectId("5c10f3735d38908db52796a5"),
"name" : "Penn Station",
"location" : { "type" : "Point", "coordinates" : [ -73.99408, 40.75057 ] }
}
{
"_id" : ObjectId("5c10f3735d38908db52796a6"),
"name" : "10gen Office",
"location" : { "type" : "Point", "coordinates" : [ -73.99171, 40.738868 ] }
}
{
"_id" : ObjectId("5c10f3735d38908db52796a9"),
"name" : "City Bakery ",
"location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
}
{
"_id" : ObjectId("5c10f3735d38908db52796aa"),
"name" : "Splash Bar",
"location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
}
{
"_id" : ObjectId("5c10f3735d38908db52796ab"),
"name" : "Momofuku Milk Bar",
"location" : { "type" : "Point", "coordinates" : [ -73.985839, 40.731698 ] }
}
Fetching all Documents within a 400 Meter radius from [-73.99171, 40.738868] would look like this using
GeoJSON:
{
$geoNear: {
maxDistance: 400,
num: 10,
near: { type: "Point", coordinates: [-73.99171, 40.738868] },
spherical:true,
key: "location",
distanceField: "distance"
}
}
resulting in the following 3 Documents.
{
"_id" : ObjectId("5c10f3735d38908db52796a6"),
"name" : "10gen Office",
"location" : { "type" : "Point", "coordinates" : [ -73.99171, 40.738868 ] }
"distance" : 0.0 // Meters
}
{
"_id" : ObjectId("5c10f3735d38908db52796a9"),
"name" : "City Bakery ",
"location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
"distance" : 69.3582262492474 // Meters
}
{
"_id" : ObjectId("5c10f3735d38908db52796aa"),
"name" : "Splash Bar",
"location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
"distance" : 69.3582262492474 // Meters
}
Using legacy coordinate pairs one operates upon radians as discussed before. Assume we use Metrics.KILOMETERS
when constructing the geoNear command. The Metric will make sure the distance multiplier is set correctly, so
the command is rendered like
{
$geoNear: {
maxDistance: 0.0000627142377, // 400 Meters
distanceMultiplier: 6378.137,
num: 10,
near: [-73.99171, 40.738868],
spherical:true,
key: "location",
distanceField: "distance"
}
}
Please note the calculated distance now uses Kilometers instead of Meters as unit of measure,
so we need to take it times 1000 to match up to Meters as in the GeoJSON variant. Still as we've been requesting the
Distance in Metrics.KILOMETERS the Distance.getValue()
reflects exactly this.
{
"_id" : ObjectId("5c10f3735d38908db52796a6"),
"name" : "10gen Office",
"location" : { "type" : "Point", "coordinates" : [ -73.99171, 40.738868 ] }
"distance" : 0.0 // Kilometers
}
{
"_id" : ObjectId("5c10f3735d38908db52796a9"),
"name" : "City Bakery ",
"location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
"distance" : 0.0693586286032982 // Kilometers
}
{
"_id" : ObjectId("5c10f3735d38908db52796aa"),
"name" : "Splash Bar",
"location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
"distance" : 0.0693586286032982 // Kilometers
}
- Author:
- Oliver Gierke, Thomas Darimont, Christoph Strobl, Mark Paluch
-
Method Summary
Modifier and TypeMethodDescriptiondistanceMultiplier(double distanceMultiplier) Configures aCustomMetricwith the given multiplier.Get theCollationto use along with thequery(Query).Returns the maximumDistance.Returns theMetricunderlying the actual query.Returns the maximumDistance.com.mongodb.ReadConcernGet theReadConcernto use.com.mongodb.ReadPreferenceGet theReadPreferenceto use.getSkip()Will cause the results' distances being returned in the given metric.Will cause the results' distances being returned in kilometers.inMiles()Will cause the results' distances being returned in miles.booleanReturns whether spharical values will be returned.limit(long limit) Configures the maximum number of results to return.maxDistance(double maxDistance) Sets the max distance results shall have from the configured origin.maxDistance(double maxDistance, Metric metric) Sets the maximum distance supplied in a given metric.maxDistance(Distance distance) Sets the maximum distance to the givenDistance.minDistance(double minDistance) Sets the minimum distance results shall have from the configured origin.minDistance(double minDistance, Metric metric) Sets the minimum distance supplied in a given metric.minDistance(Distance distance) Sets the minimum distance to the givenDistance.static NearQuerynear(double x, double y) Creates a newNearQuerystarting near the given coordinates.static NearQuerystatic NearQuerystatic NearQueryAdds an actual query to theNearQueryto restrict the objects considered for the actual near operation.skip(long skip) Configures the number of results to skip.spherical(boolean spherical) Configures whether to return spherical values for the actual distance.org.bson.DocumentReturns theDocumentbuilt by theNearQuery.Configures thePageableto use.withReadConcern(com.mongodb.ReadConcern readConcern) Configures the query to use the givenReadConcernunless the underlyingquery(Query)specifiesanother one.withReadPreference(com.mongodb.ReadPreference readPreference) Configures the query to use the givenReadPreferenceunless the underlyingquery(Query)specifiesanother one.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.springframework.data.mongodb.core.ReadConcernAware
hasReadConcernMethods inherited from interface org.springframework.data.mongodb.core.ReadPreferenceAware
hasReadPreference
-
Method Details
-
near
Creates a newNearQuerystarting near the given coordinates.- Parameters:
x-y-- Returns:
-
near
Creates a newNearQuerystarting at the given coordinates using the givenMetricto adapt given values to further configuration. E.g. setting amaxDistance(double)will be interpreted as a value of the initially setMetric.- Parameters:
x-y-metric- must not be null.- Returns:
-
near
Creates a newNearQuerystarting at the givenPoint.
NOTE: There is a difference in usingPointversusGeoJsonPoint.Pointvalues are rendered as coordinate pairs in the legacy format and operate upon radians, whereas theGeoJsonPointuses according to its specification meters as unit of measure. This may lead to different results when using aneutral Metric.- Parameters:
point- must not be null.- Returns:
- new instance of
NearQuery.
-
near
Creates aNearQuerystarting near the givenPointusing the givenMetricto adapt given values to further configuration. E.g. setting amaxDistance(double)will be interpreted as a value of the initially setMetric.
NOTE: There is a difference in usingPointversusGeoJsonPoint.Pointvalues are rendered as coordinate pairs in the legacy format and operate upon radians, whereas theGeoJsonPointuses according to its specification meters as unit of measure. This may lead to different results when using aneutral Metric.- Parameters:
point- must not be null.metric- must not be null.- Returns:
- new instance of
NearQuery.
-
getMetric
Returns theMetricunderlying the actual query. If no metric was set explicitlyMetrics.NEUTRALwill be returned.- Returns:
- will never be null.
-
limit
Configures the maximum number of results to return.- Parameters:
limit-- Returns:
- Since:
- 2.2
-
skip
Configures the number of results to skip.- Parameters:
skip-- Returns:
-
with
Configures thePageableto use.- Parameters:
pageable- must not be null- Returns:
-
maxDistance
Sets the max distance results shall have from the configured origin. If aMetricwas set before the given value will be interpreted as being a value in that metric. E.g.NearQuery query = near(10.0, 20.0, Metrics.KILOMETERS).maxDistance(150);
Will set the maximum distance to 150 kilometers.- Parameters:
maxDistance-- Returns:
-
maxDistance
Sets the maximum distance supplied in a given metric. Will normalize the distance but not reconfigure the query's resultMetricif one was configured before.- Parameters:
maxDistance-metric- must not be null.- Returns:
-
maxDistance
Sets the maximum distance to the givenDistance. Will set the returnedMetricto be the one of the givenDistanceifMetricwasMetrics.NEUTRALbefore.- Parameters:
distance- must not be null.- Returns:
-
minDistance
Sets the minimum distance results shall have from the configured origin. If aMetricwas set before the given value will be interpreted as being a value in that metric. E.g.NearQuery query = near(10.0, 20.0, Metrics.KILOMETERS).minDistance(150);
Will set the minimum distance to 150 kilometers.- Parameters:
minDistance-- Returns:
- Since:
- 1.7
-
minDistance
Sets the minimum distance supplied in a given metric. Will normalize the distance but not reconfigure the query's resultMetricif one was configured before.- Parameters:
minDistance-metric- must not be null.- Returns:
- Since:
- 1.7
-
minDistance
Sets the minimum distance to the givenDistance. Will set the returnedMetricto be the one of the givenDistanceif noMetricwas set before.- Parameters:
distance- must not be null.- Returns:
- Since:
- 1.7
-
getMaxDistance
Returns the maximumDistance.- Returns:
-
getMinDistance
Returns the maximumDistance.- Returns:
- Since:
- 1.7
-
distanceMultiplier
Configures aCustomMetricwith the given multiplier.- Parameters:
distanceMultiplier-- Returns:
-
spherical
Configures whether to return spherical values for the actual distance.- Parameters:
spherical-- Returns:
-
isSpherical
public boolean isSpherical()Returns whether spharical values will be returned.- Returns:
-
inKilometers
Will cause the results' distances being returned in kilometers. SetsdistanceMultiplier(double)andspherical(boolean)accordingly.- Returns:
-
inMiles
Will cause the results' distances being returned in miles. SetsdistanceMultiplier(double)andspherical(boolean)accordingly.- Returns:
-
in
Will cause the results' distances being returned in the given metric. SetsdistanceMultiplier(double)accordingly as well asspherical(boolean)if the givenMetricis notMetrics.NEUTRAL.- Parameters:
metric- the metric the results shall be returned in. UsesMetrics.NEUTRALif null is passed.- Returns:
-
query
Adds an actual query to theNearQueryto restrict the objects considered for the actual near operation.- Parameters:
query- must not be null.- Returns:
-
getSkip
- Returns:
- the number of elements to skip.
-
getCollation
Get theCollationto use along with thequery(Query).- Returns:
- the
Collationif set. null otherwise. - Since:
- 2.2
-
withReadConcern
Configures the query to use the givenReadConcernunless the underlyingquery(Query)specifiesanother one.- Parameters:
readConcern- must not be null.- Returns:
- this.
- Since:
- 4.1
-
withReadPreference
Configures the query to use the givenReadPreferenceunless the underlyingquery(Query)specifiesanother one.- Parameters:
readPreference- must not be null.- Returns:
- this.
- Since:
- 4.1
-
getReadConcern
Get theReadConcernto use. Will return the underlyingqueriesReadConcernif present or the one defined on thereadConcernitself.- Specified by:
getReadConcernin interfaceReadConcernAware- Returns:
- can be null if none set.
- Since:
- 4.1
- See Also:
-
getReadPreference
Get theReadPreferenceto use. Will return the underlyingqueriesReadPreferenceif present or the one defined on thereadPreferenceitself.- Specified by:
getReadPreferencein interfaceReadPreferenceAware- Returns:
- can be null if none set.
- Since:
- 4.1
- See Also:
-
toDocument
public org.bson.Document toDocument()Returns theDocumentbuilt by theNearQuery.- Returns:
-