我是GoLang & MongoDB的新手。我正在尝试使用mgo来理解它们之间的关系。然而,我找不到一个合适的例子来说明如何使用mgo从mongo中获取被引用的对象。我听说过populate方法,但不知道mgo如何使用它。有没有人能对此一目了然?
发布于 2019-01-08 10:26:51
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)
}
}发布于 2018-12-28 17:22:11
你的问题太宽泛了,但是一般来说,如果你想用一个查询来获取“引用的”对象,你必须使用MongoDB的Aggregation framework,特别是lookup阶段。
聚合框架可以通过Collection.Pipe()方法在mgo中使用。
有关示例,请参阅Get a value in a reference of a lookup with MongoDB and Golang。
更多的例子:
How to get the count value using $lookup in mongodb using golang?
https://stackoverflow.com/questions/53955748
复制相似问题