繁体   English   中英

猫鼬查询“热门”帖子

[英]Mongoose query for “hot” posts

我想根据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)]

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

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 */] } 

然后,您可以查询:

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

如果您的描述/标题经常更改,那么您无需$push整个文档,而只需推送ID并将其用于帖子的$in查询中即可保证最新数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM