MongoDB предоставляет $lookup
для выполнения левого внешнего соединения.Ниже приведен пример использования 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)
}
}