Golang MongoDB聚合 [英] Golang mongodb aggregation

查看:127
本文介绍了Golang MongoDB聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组用户.用户有一个int64"id",并说"avatar","name"和其他用户ID的数组. 我想要实现的是查询SINGLE用户,但与其获取带有其朋友ID的数组,不如获取一个包含其姓名和头像的朋友的数组.如何在golang中实现它?我已经找到了我需要的某种东西-查找"功能,但是我不明白如何正确使用它.

I have a collection of users. User have an int64 "id", and lets say "avatar", "name" and an array of other users ids. 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. How to achieve it in golang? I have found some kind of what I need - "lookup" function, but I cannot understand how to use it right.

推荐答案

您不能应用 $ unwind 首先.

You cannot apply $lookup to array directly, but you can to $unwind it first.

没有示例文档,下面的代码段是一种通用方法:

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)

我应该提到聚合/管道返回的是bson.M,而不是水合的User对象. Mongo毕竟不是关系数据库.

I should mention that aggregation/pipe returns bson.M, not hydrated User objects. Mongo is not a relational database after all.

这篇关于Golang MongoDB聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆