简体   繁体   中英

Does MongoDB provide the distance to point with $nearSphere operator?

The $nearSphere MongoDB operator is able to return the documents near to a given point (specified as parameter of the operator) sorted by incresing distance.

However, how to get the actual distance? Is there any mean of getting this using MongoDB functionality? Either with $nearSphere (although I have checked its documentation and I haven't found this information) or with other mechanisms (maybe the aggregation framework?)

Thanks!

With aggregation you can use the $geoNear stage to provide both spherical geometry and return the distance.

Example from the docs:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM