how to get distance using $within $centerSphere

i'm using $within $centerSphere to get only the documents of collection that are inside the circle with a certain radius.

The query that i use is:

{"value.pos":{"$within":{"$centerSphere":
[[40.6861735,14.777354800000012],0.0007839325190887568]}}}

where 0.0007839325190887568 = 5 * 6378.1 ( earth radius ).

What i need is to show the distance between the point and the position of the element of the document.

I'm using mongodb driver for nodejs.

After receiving the distance i need to order the results programmatically only and just only the user want it.

I can't use mongoose because i need to change too much my existing code so i want to use standard mongodb driver.

Is there a solution?

Thanks!

$within has been deprecated since 2.4. To do what you want, make sure you are running at least MongoDB 2.4 and use geoNear in an aggregation pipeline stage. Using aggregation is necessary to get the distance in the results.

db.places.aggregate([
    {
        $geoNear: {
            near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
            distanceField: "distance",
            maxDistance: < your distance in meters>,
            spherical: true
        }
    }
])

Make sure you have a 2dsphere index on value.pos.