【发布时间】:2023-01-14 03:09:48
【问题描述】:
我目前正在使用聚合来获取创建帖子的用户并填充帖子结构中的用户字段。我想找到所有 cmets,其中 post_id: _id _id 是帖子的 _id。
这是我当前的代码,当前返回用户的帖子。
func GetPostFeed() ([]models.PostResponse, error) {
postCollection := DB.Database("wecrypto").Collection("posts")
var postFeed []models.PostResponse
lookupStage := bson.D{
bson.E{
Key: "$lookup",
Value: bson.M{
"from": "users",
"localField": "user_id",
"foreignField": "_id",
"as": "user",
},
},
}
//groupStage := bson.D{
// bson.E{
// Key: "$group",
// Value: bson.M{
// "_id": "$post_id",
// "$commentCount": bson.E{
// Key: "$sum",
// Value: 1,
// },
// },
// },
//}
unwindStage := bson.D{
bson.E{
Key: "$unwind",
Value: bson.M{
"path": "$user",
},
},
}
filterCursor, err := postCollection.Aggregate(context.Background(), mongo.Pipeline{lookupStage, groupStage, unwindStage})
if err != nil {
return nil, err
}
err = filterCursor.All(context.Background(), &postFeed)
if err != nil {
return nil, err
}
return postFeed, nil
}
预期结果:
{
"id": "61ef6586a629895408c149b8",
"body": "This is the body of the test posts",
"isTrending": false,
"tags": [],
"user": {
"id": "61eb91801579dd486ba0099e",
"username": "bob",
"avatarURL": "string.url"
},
"mentions": [],
"commentCount": 4 <----- this is what I want.
}
【问题讨论】:
-
GetPostFeed()函数返回值还是错误? -
@hisam 它返回错误或数组。
标签: mongodb go aggregation