JSON pipeline stages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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