Skip to content

Instantly share code, notes, and snippets.

@Lebski
Last active July 28, 2022 03:37
Show Gist options
  • Save Lebski/8f9b5992fec0bf175285f1c13b1e5051 to your computer and use it in GitHub Desktop.
Save Lebski/8f9b5992fec0bf175285f1c13b1e5051 to your computer and use it in GitHub Desktop.
MongoDb gesospital query with golang (with mongo-go-driver)
=== RUN TestGetPointsByDistance
Inserted new Point. f0cfed41-fba5-4a2d-8179-9737b631d3c1
<nil>
[{2d91d952-2825-4a28-ae53-5a58656c4f68 {Point [12.002 12]}} {f0cfed41-fba5-4a2d-8179-9737b631d3c1 {Point [12.002 12]}}]
--- PASS: TestGetPointsByDistance (0.00s)
package dbs
import (
"context"
"fmt"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
)
// We need this type so we can store it in our mongodb db and do geospatial queries
// https://docs.mongodb.com/manual/geospatial-queries/
type Location struct {
GeoJSONType string `json:"type" bson:"type"`
Coordinates []float64 `json:"coordinates" bson:"coordinates"`
}
func NewLocation(lat, long float64) Location {
return Location{
"Point",
[]float64{lat, long},
}
}
type Point struct {
Id string `json:"id" bson:"_id"`
Location Location `json:"location" bson:"location"`
}
func AddPoint(point Point) (string, error) {
point.Id = uuid.New().String()
insertResult, err := PointCollection.InsertOne(context.TODO(), point)
if err != nil {
fmt.Printf("Could not insert new Point. Id: %s\n", point.Id)
return "", err
}
fmt.Printf("Inserted new Point. Id: %s\n", insertResult.InsertedID)
return point.Id, nil
}
func GetPointsByDistance(location Location, distance int) ([]Point, error) {
var results []Point
// You have to build an index fo this stuff
//db.Points.createIndex( { <location field> : "2dsphere" } )
filter := bson.D{
{"location",
bson.D{
{"$near", bson.D{
{"$geometry", location},
{"$maxDistance", distance},
}},
}},
}
cur, err := PointCollection.Find(context.TODO(), filter)
if err != nil {
return []Point{}, err
}
for cur.Next(context.TODO()) {
var elem Point
err := cur.Decode(&elem)
if err != nil {
fmt.Println("Could not decode Point")
return []Point{}, err
}
results = append(results, elem)
}
return results, nil
}
package dbs
import (
"fmt"
a "github.com/stretchr/testify/assert"
"testing"
)
func TestGetPointsByDistance(t *testing.T) {
assert := a.New(t)
var testPoint = Point{Location: NewLocation(12.002, 12)}
_, err := AddPoint(testPoint)
assert.NoError(err)
points, err := GetPointsByDistance(NewLocation(12.002, 12), 50)
assert.NoError(err)
fmt.Println(err)
fmt.Println(points)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment