Using MongoDB pipelines with Golang

Thiago trennepohl
2 min readFeb 23, 2018

--

Updated post can be found at

https://trennepohl.github.io/go_mongo_aggregations/

In my journey of learning Golang and creating rest API’s I bumped into a problem where I needed to use MongoDb’s pipelines to aggregate data and render a chart with Chartjs, which is an amazing chart library by the way.

Then I wondered if the mgo library supports pipelines, and it does!

Here’s an example of how to use it.

With the data set above, imagine that I would like to count how many records a customer has.

For that, I’ll declare a variable result which is a slice of bson.M , but it can be an array of map[string]interface{} as well.

var result []bson.M

Then, I’ll build my pipeline query.

pipeline := []bson.M{bson.M{ "$group": bson.M{ "_id": "$cust_id", "count": bson.M{ "$sum": 1}}}}

Execute the query.

conn.Pipe(pipeline).All(&result)

And the result will be an array of bson.M with your beautifully aggregated data ❤.

[map[_id:xyz1 count:3] map[_id:abc1 count:2]]

But what if I want to only the abc1 client records to be returned? Thats easy! i will just simply add a “Match” step before “Grouping it”.

pipeline := []bson.M{bson.M{ "$match": bson.M{ "cust_id": "abc1" } }, bson.M{ "$group": bson.M{ "_id": "$cust_id", "count": bson.M{ "$sum": 1}}}}

And shazam, magic was made.

[map[_id:abc1 count:2]]

For those who wants to know more about mongo’s pipelines, take a read at:
https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/ .

I hope it helps someone :)

--

--