I am new to GoLang & MongoDB. I am trying to understand their relation using mgo. However , I am unable to find a suitable example on how to fetch referenced objects from mongo in Go using mgo. I have heard about populate method but no idea how mgo uses it. Can anyone throw light on the same?
Your question is too broad, but in general if you want to fetch "referenced" object with a single query, you have to use MongoDB's Aggregation framework, specifically the lookup stage.
The aggregation framework can be used from mgo
with the Collection.Pipe()
method.
For an example, see Get a value in a reference of a lookup with MongoDB and Golang.
Some more examples:
How to get the count value using $lookup in mongodb using golang?
MongoDB provides $lookup
to perform left outer join. Below is an example using mgo.
func TestLookup(t *testing.T) {
var err error
uri := "mongodb://localhost/stackoverflow?replicaSet=replset"
dialInfo, _ := mgo.ParseURL(uri)
session, _ := mgo.DialWithInfo(dialInfo)
c := session.DB("stackoverflow").C("users")
pipeline := `
[{
"$lookup": {
"from": "addresses",
"localField": "address_id",
"foreignField": "_id",
"as": "address"
}
}, {
"$unwind": {
"path": "$address"
}
}, {
"$project": {
"_id": 0,
"name": "$name",
"address": "$address.address"
}
}]
`
var v []map[string]interface{}
var results []bson.M
json.Unmarshal([]byte(pipeline), &v)
if err = c.Pipe(v).All(&results); err != nil {
t.Fatal(err)
}
for _, doc := range results {
t.Log(doc)
}
}