【问题标题】:GOLANG + MONGODB: Get count of all comments in a postGOLANG + MONGODB:计算帖子中的所有评论
【发布时间】: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


【解决方案1】:

如果您的帖子和彗星处于不同的架构中并且通过“外键”或 ID 链接,即类似这样的东西......

// Posts
[
{
    _id: 1
    content: 'Post 1'
},
{
    _id: 2
    content: 'Post 2'
}
]

// Comments
[
{
    _id: 1,
    post: 1,
    content: 'Content 1'
},
{
    _id: 2,
    post: 1,
    content: 'Content 1'
}
]

然后你可以像这样计算管道中每个帖子的 cmets 数量

[
  ...
{
          $lookup: {
            from: 'comments',
            localField: '_id',
            foreignField: 'post',
            as: 'postComments'
          }
        },
         {
          $project: {
            _id: 1,
            content: 1,
              commentCount: {
                $size: '$postComments'
              }
          }
        }
]

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    相关资源
    最近更新 更多