Skip to content

Instantly share code, notes, and snippets.

@casoetan
Forked from sindbach/mongodb_lookup.go
Created November 30, 2017 09:49
Show Gist options
  • Save casoetan/204a4e046e2e0d1d914155acc8365c66 to your computer and use it in GitHub Desktop.
Save casoetan/204a4e046e2e0d1d914155acc8365c66 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment