Skip to content

Instantly share code, notes, and snippets.

@divjotarora
Created March 6, 2020 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divjotarora/33e1b5dd6d22f1bcfffce427ae61dc32 to your computer and use it in GitHub Desktop.
Save divjotarora/33e1b5dd6d22f1bcfffce427ae61dc32 to your computer and use it in GitHub Desktop.
JSON pipeline stages
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
geoNearStage := `
{
"$geoNear": {
"includeLocs": "location",
"distanceField": "distance",
"maxDistance": 1000,
"spherical": true,
"near": {
"type": "Point",
"coordinates": [10, 10]
}
}
}`
countStage := `
{
"$count": "number"
}`
ctx := context.TODO()
uri := "mongodb://localhost:27017"
opts := options.Client().ApplyURI(uri)
client, err := mongo.Connect(ctx, opts)
if err != nil {
panic(err)
}
defer client.Disconnect(ctx)
coll := client.Database("foo").Collection("bar")
pipeline := buildPipeline(geoNearStage, countStage)
cursor, err := coll.Aggregate(ctx, pipeline)
if err != nil {
panic(err)
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
fmt.Println(cursor.Current)
}
}
func buildPipeline(stages ...string) mongo.Pipeline {
var pipeline mongo.Pipeline
for idx, stage := range stages {
var stageDoc bson.D
if err := bson.UnmarshalExtJSON([]byte(stage), false, &stageDoc); err != nil {
panic(fmt.Sprintf("error unmarshalling stage %d: %v", idx, err))
}
pipeline = append(pipeline, stageDoc)
}
return pipeline
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment