Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 251
Graykos Avatar asked Feb 04 '23 21:02

Graykos


1 Answers

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)

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

like image 74
Alex Blex Avatar answered Feb 08 '23 15:02

Alex Blex