MongoDB - Comment Upvoting/Downvoting with Aggregation Pipeline

前端 未结 1 1949
予麋鹿
予麋鹿 2021-01-22 10:38

I\'m trying to implement an upvote/downvote mechanism for comments (similar to the upvoting/downvoting mechanism found on reddit). I have a separate collection called comm

相关标签:
1条回答
  • 2021-01-22 11:29

    you can do it with the following pipeline update but it requires that the upvotes and downvotes arrays exist. even if it's just empty.

    var comment_id = ObjectId("5e5983102328a83d1a4b541f");
    var user_id = ObjectId("5e5983102328a83d1a4b53e5");
    
    db.commentReputation.update(
        {
            commentId: comment_id
        },
        [
            {
                $set: {
                    upvotes: {
                        $cond: [
                            { $in: [user_id, '$upvotes'] },
                            { $setDifference: ['$upvotes', [user_id]] },
                            { $setUnion: ['$upvotes', [user_id]] }
                        ]
                    }
                }
            },
            {
                $set: {
                    downvotes: {
                        $cond: [
                            { $in: [user_id, '$downvotes'] },
                            { $setDifference: ['$downvotes', [user_id]] },
                            '$downvotes'
                        ]
                    }
                }
            }
        ]
    );
    
    0 讨论(0)
提交回复
热议问题