如何订购 GeoSpatial 搜索,并在结果中包含距离

How to order GeoSpatial searches, and include distance in results

我本来问了一个问题,但答案很明显。来自 MongoDB:

$near always returns the documents sorted by distance. Any other sort order requires to sort the documents in memory, which can be inefficient. To return results in a different sort order, use the $geoWithin operator and the sort() method.

我在文档中唯一没有看到的是如何在结果中包含距离。

看来要用聚合框架,找不到,为了包含距离:

distanceField The output field that contains the calculated distance. To specify a field within an embedded document, use dot notation.

http://docs.mongodb.org/manual/reference/operator/aggregation/geoNear/#pipe._S_geoNear

示例:

db.places.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
        distanceField: "dist.calculated",
        maxDistance: 2,
        query: { type: "public" },
        includeLocs: "dist.location",
        num: 5,
        spherical: true
     }
   }
])

聚合returns以下:

{
   "_id" : 8,
   "name" : "Sara D. Roosevelt Park",
   "type" : "public",
   "location" : {
      "type" : "Point",
      "coordinates" : [ -73.9928, 40.7193 ]
   },
   "dist" : {
      "calculated" : 0.9539931676365992,
      "location" : {
         "type" : "Point",
         "coordinates" : [ -73.9928, 40.7193 ]
      }
   }
}