$unionwith aggregation pipeline stage in golang

Hi All,

I am looking for any sample code for $unionwith aggregation pipeline in golang.
basically how would the below aggregate statement in golang look like:
aggregate([ { $project: { state: 1, _id: 0 } }, { $unionWith: { coll: “warehouses”, pipeline: [ { $project: { state: 1, _id: 0 } } ]} } ])

1 Like

Hi @Nitin_Mukheja_1!

Thanks for posting your question. Here’s a Quick Start tutorial written by my colleague @nraboy on how to form an Aggregation Pipeline with MongoDB and Golang.

It seems that you declare your stages, then use the Aggregate operation to execute your pipeline (sample code taken from linked quick start above):

matchStage := bson.D{{"$match", bson.D{{"podcast", id}}}}
groupStage := bson.D{{"$group", bson.D{{"_id", "$podcast"}, {"total", bson.D{{"$sum", "$duration"}}}}}}

showInfoCursor, err := episodesCollection.Aggregate(ctx, mongo.Pipeline{matchStage, groupStage})

Please let us know if this helps or if you have any other questions!

1 Like

Hello there. I’m having the same problem traducing my $unionWith mongo query to Golang driver. That " pipeline: [] " part is killing me. What’s the logic to follow in order to get the traductions? Is there a syntax guide?

My mongo query looks like this:
$unionWith: {coll: “packets”,
pipeline: [
{$match: {srcmac: “xx.xx.xx.xx.xx.xx”}},
{$group: {_id: “$protoip”, qty: {$sum: 1}}}