簡體   English   中英

Golang MongoDB聚合

[英]Golang mongodb aggregation

我有一組用戶。 用戶有一個int64“ id”,並說“ avatar”,“ name”和其他用戶ID的數組。 我想要實現的是查詢SINGLE用戶,但是與其獲取一個帶有其朋友ID的數組,不如獲取一個包含其姓名和頭像的朋友的數組。 如何在golang中實現它? 我已經找到了所需的某種東西-“查找”功能,但是我不明白如何正確使用它。

您不能直接將$ lookup應用於數組,但可以先對其進行$ unwind

如果沒有示例文檔,則下面的代碼段是一種通用方法:

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不是關系數據庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM