Mongoose查询“热门”帖子

时间:2017-11-13 22:04:22

标签: javascript node.js mongodb mongoose trending

我想根据likesdate显示数据库中的帖子列表,想一想基本的“趋势”项目页面。

我想使用类似score = likes / daysSinceCreation的公式,然后根据此分数获得前10个帖子。

如何使用mongoDB / Mongoose添加该排序函数?

Posts.find().sort(???).limit(10).then(posts => console.log(posts));

目前我可以在上周获得热门帖子(查找创建日期是否大于上周并按分数排序),但如何在不获取数据库中的所有项目的情况下实现更复杂的排序功能?

例如: 今天是星期五

ID  CREATION_DAY    LIKES
 1  Monday          4     // score is 5/5 = 0
 2  Tuesday         10    // score is 10/4 = 2
 3  Wednesday       3     // score is 3/3 = 1
 4  Thursday        20    // score is 20/2 = 10
 5  Friday          5     // score is 5/1 = 5

ID的排序列表为:[4 (Th), 5 (Fr), 2 (Tu), 3 (We), 1(Mo)]

1 个答案:

答案 0 :(得分:1)

这将在“trendingposts”表中创建一个新文档:

const fiveDaysAgo = new Date(Date.now() - (5 * 24 * 60 * 60 * 1000));
const oid = new ObjectId();
const now = new Date();

Posts.aggregate([
    {
        $match: {
            createdAt: {
                $gte: fiveDaysAgo
            },
            score: {
                $gt: 0
            }
        }
    },
    {
        $project: {
            _id: true,
            createdAt: true,
            updatedAt: true,
            title: true,
            description: true,
            score: true,
            trendScore: {
                $divide: [ "$score", {$subtract: [new Date(), "$createdAt"]} ]
            }
        }
    },
    {
        $sort: {
            trendScore: -1
        }
    },
    {
        $limit: 10
    },
    {
        $group: {
            _id: { $min: oid },
            evaluatedAt: { $min: now },
            posts: { $push: "$$ROOT"}
        }
    },
    {
        $out: "trendingposts"
    }
])
    .then(...)

有几点需要注意:

  1. 如果使用Mongo 3.4+,$ project阶段也可以写成:

    {
        $addFields: {
            trendScore: {
                $divide: [ "$score", {$subtract: [new Date(), "$createdAt"]} ]
            }
        }
    },
    
  2. { $min: now }只是在每个文档上获取now的最小值,即使它们对所有文档都是相同的值。

  3. "$$ROOT"是整个当前文档。这意味着您的最终结果将是具有以下形式的单个对象:

    {
        "_id" : ObjectId("5a0a2fe912a325eb331f2759"),
        "evaluatedAt" : ISODate("2017-11-13T23:51:56.051Z"),
        "posts" : [/*10 `post` documents, sorted by trendScore */]
    }
    
  4. 然后您可以使用以下方式查询:

    TrendingPosts.findOne({})
        .sort({_id: -1})
        .then(trendingPost => console.log(trendingPost));
    

    如果您的说明/标题经常更改,而不是$push整个文档,您只需推送ID并使用它们对帖子进行$in查询,以确保最新数据。