[英]Golang mongodb aggregation
I have a collection of users. 我有一组用户。 User have an int64 "id", and lets say "avatar", "name" and an array of other users ids.
用户有一个int64“ id”,并说“ avatar”,“ name”和其他用户ID的数组。 What I want to achieve is to query SINGLE user, but instead of getting an array with his friends ids I want to get an array of his friends, containing their names and avatars.
我想要实现的是查询SINGLE用户,但是与其获取一个带有其朋友ID的数组,不如获取一个包含其姓名和头像的朋友的数组。 How to achieve it in golang?
如何在golang中实现它? I have found some kind of what I need - "lookup" function, but I cannot understand how to use it right.
我已经找到了所需的某种东西-“查找”功能,但是我不明白如何正确使用它。
You cannot apply $lookup to array directly, but you can to $unwind it first. 您不能直接将$ lookup应用于数组,但可以先对其进行$ unwind 。
Without example documents, the code snippet below is rather a general approach: 如果没有示例文档,则下面的代码段是一种通用方法:
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)
I should mention that aggregation/pipe returns bson.M
, not hydrated User objects. 我应该提到聚合/管道返回
bson.M
,而不是水合的User对象。 Mongo is not a relational database after all. 毕竟,Mongo不是关系数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.