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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With