K
K
Konstantin2016-09-07 02:57:03
MongoDB
Konstantin, 2016-09-07 02:57:03

How in MongoDB (mgo) to display the nearest documents with the distance to it?

If I get without distance like this:

err = c.Find(bson.M{
                            "location": bson.M{
                              "$nearSphere": bson.M{
                                "$geometry": bson.M{
                                  "type":        "Point",
                                  "coordinates": []float64{lat, long},
                                },
                                "$maxDistance": scope,
                              },
                            },
                          }).All(&places)

tell me how else to get the distance to each document?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2016-09-07
@happy_yar

$geoNear aggregator can do this

err = c.Pipe(bson.M{
                            "$geoNear": bson.M{
                                "spherical": "true",
                            	"distanceField": "distance",
                                "near": bson.M{
                                  "type":        "Point",
                                  "coordinates": []float64{lat, long},
                                },
                                "maxDistance": scope,                            
                              },
                          }).All(&places)

distance will be in the fielddistance

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question