Skip to content

Instantly share code, notes, and snippets.

@divjotarora

divjotarora/main.go Secret

Created Mar 6, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.