Skip to content

Instantly share code, notes, and snippets.

@sindbach
Created April 15, 2016 00:40
Show Gist options
  • Save sindbach/efeda4b6b614574ee08229ce4a183882 to your computer and use it in GitHub Desktop.
Save sindbach/efeda4b6b614574ee08229ce4a183882 to your computer and use it in GitHub Desktop.
A simple example of how to use $lookup in Golang using mgo.
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
func main() {
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
collection := session.DB("database").C("collection")
pipeline := []bson.M{
bson.M{"$match": bson.M{"_id": bson.ObjectIdHex("56b9df0c1e930a99cb2c33e9")}},
bson.M{"$lookup": bson.M{ "from": "localCollection", "localField": "localField", "foreignField": "foreignField", "as": "resultField"}},
}
pipe := collection.Pipe(pipeline)
resp := []bson.M{}
err = pipe.All(&resp)
if err != nil {
fmt.Println("Errored: %#v \n", err)
}
fmt.Println(resp)
}
@pitis
Copy link

pitis commented Jan 26, 2023

what about adding pipelines to the lookup itself?

@sindbach
Copy link
Author

Hi @pitis,
I'd assumed that you're referring to specifying an extra pipeline in the $lookup stage as mentioned here: https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/#join-conditions-and-subqueries-on-a-joined-collection

Yes you should be able to, just specify the pipeline parameter as []bson.M{} with the individual stages as bson.M{}.

@pitis
Copy link

pitis commented Jan 28, 2023

hey there @sindbach thank you very much for your fast reply!

Unfortunately, I am new to Go and it was pretty hard for me to come with the exact pipeline, so I just wanted to state here for new people that MongoDB Compass has an "Export to Langauge" button which can create the whole exact pipeline.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment