Created
May 13, 2020 20:25
-
-
Save trennepohl/bd756c29b31398cca0c7212bb6e9961b to your computer and use it in GitHub Desktop.
Mongodb pipeline example
This file contains hidden or 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" | |
"log" | |
"time" | |
) | |
type OrderStatusTotal struct { | |
ID string `bson:"_id"` | |
Total int `bson:"total"` | |
} | |
func main(){ | |
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")) | |
if err != nil { | |
fmt.Errorf("failed to create a mongo client %s", err.Error()) | |
log.Println(err.Error()) | |
return | |
} | |
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second) | |
collection := client.Database("ecomerce").Collection("orders") | |
err = client.Connect(ctx) | |
if err != nil { | |
log.Println(err.Error()) | |
fmt.Errorf("connection to mongodb failed %s", err.Error()) | |
return | |
} | |
pipelineResult := make([]OrderStatusTotal, 0) | |
pipeline := make([]bson.M, 0) | |
groupStage := bson.M{ | |
"$group": bson.M{ | |
"_id": "$status", | |
"total": bson.M{"$sum": 1}, | |
}, | |
} | |
matchStage := bson.M{ | |
"$match": bson.M{ | |
"cust_id": "abc1", | |
}, | |
} | |
pipeline = append(pipeline, matchStage,groupStage) | |
data, err := collection.Aggregate(ctx, pipeline) | |
if err != nil { | |
log.Println(err.Error()) | |
fmt.Errorf("failed to execute aggregation %s", err.Error()) | |
return | |
} | |
err = data.All(ctx, &pipelineResult) | |
if err != nil { | |
log.Println(err.Error()) | |
fmt.Errorf("failed to decode results", err.Error()) | |
return | |
} | |
fmt.Printf("%+v\n", pipelineResult) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment