Gra*_*kos 2 lookup go mongodb mgo aggregation-framework
我有一个用户集合.用户有一个int64"id",让我们说"avatar","name"和其他用户id的数组.我想要实现的是查询SINGLE用户,但我没有得到他的朋友ID的数组,而是想得到他的朋友的数组,包含他们的名字和头像.如何在golang中实现它?我找到了一些我需要的东西 - "查找"功能,但我无法理解如何正确使用它.
您不能直接将$ lookup应用于数组,但您可以先将它展开.
如果没有示例文档,下面的代码片段就是一种通用方法:
pipeline := []bson.M{
bson.M{"$match": bson.M{"_id": userId }},
bson.M{"$unwind": "$otherUsersIdsArrayName"},
bson.M{
"$lookup": bson.M{
"from": userCollectionName,
"localField": otherUsersIdsArrayName,
"foreignField": "id",
"as": "friend"
}
},
bson.M{"$unwind": "$friend"},
bson.M{
"$group": bson.M{
"_id": "id",
"id": bson.M{"$first": "$id"},
"name": bson.M{"$first": "$name"},
"avatar": bson.M{"$first": "$avatar"},
otherUsersIdsArrayName: bson.M{ "$push": "$friend"}
}
}
}
pipe := collection.Pipe(pipeline)
resp := []bson.M{}
err = pipe.All(&resp)
Run Code Online (Sandbox Code Playgroud)
我应该提到聚合/管道返回bson.M,而不是水合用户对象.毕竟Mongo不是关系数据库.
| 归档时间: |
|
| 查看次数: |
1438 次 |
| 最近记录: |