-1

I'm trying to get the distance between two points on a 2dsphere from MongoDB using Go.

I followed this answer and tried this

conditions["geolocation"] = bson.M{
        "$geoNear": bson.M{
            "near": bson.M{
                "type":        "Point",
                "coordinates": []float64{latitude, longitude},
            },
            "maxDistance":   rangeInMeters,
            "spherical":     true,
            "distanceField": "distance",
        },
    }

filterCursor, err := collection.Find(ctx, conditions)

But I get this error : "Invalid arguement in geo near query:near"

Mawardy
  • 3,618
  • 2
  • 33
  • 37

1 Answers1

0

The Mentioned Answer uses MongoDB aggregate function.

You can do that with golang like follows :

    stages := mongo.Pipeline{}
    getNearbyStage := bson.D{{"$geoNear", bson.M{
        "near": bson.M{
            "type":        "Point",
            "coordinates": []float64{longitude, latitude},
        },
        "maxDistance":   rangeInMeters,
        "spherical":     true,
        "distanceField": "distance",
    }}}
    stages = append(stages, getNearbyStage)

    filterCursor, err := collection.Aggregate(ctx, stages)

    if err != nil {
        log.Println(err)
        return nil, err
    }



If you want to add another query to the pipleline you can simply make another stage and append it to the stages slice

also check this quick guide on how to use Aggregation Pipelines in golang & mongo Golang & MongoDB - Data Aggregation Pipeline

MR NOBODY
  • 13
  • 1
  • 4
Mawardy
  • 3,618
  • 2
  • 33
  • 37