2017-03-16 160 views
0

我有一组用户。用户有一个int64“id”,可以说“avatar”,“name”和其他用户ID数组。 我想要实现的是查询SINGLE用户,而不是与他的朋友ID获取数组,而是希望获得他的朋友数组,包含他们的姓名和头像。如何在golang中实现它?我找到了一些我需要的东西 - “查找”功能,但我无法理解如何正确使用它。Golang mongodb聚合

+0

这似乎是一个mongo问题,而不是一个golang问题。 https://docs.mongodb.com/v3.2/tutorial/query-documents/#query-method。它有点难以帮助你没有一些代码。 –

回答

4

您不能直接向阵列应用$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,不水合用户对象。毕竟,Mongo并不是一个关系数据库。