Skip to content

Instantly share code, notes, and snippets.

@xXPhenomXx
Forked from sindbach/mongodb_lookup.go
Created April 26, 2020 15:03
Show Gist options
  • Save xXPhenomXx/0d18e1c6fe75ae2d03215f5610948ea6 to your computer and use it in GitHub Desktop.
Save xXPhenomXx/0d18e1c6fe75ae2d03215f5610948ea6 to your computer and use it in GitHub Desktop.

Revisions

  1. @sindbach sindbach created this gist Apr 15, 2016.
    31 changes: 31 additions & 0 deletions mongodb_lookup.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    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)
    }