gpt4 book ai didi

node.js - Mongoose/MongoDB 获取一天内浏览次数最多的文章分组

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:42 26 4
gpt4 key购买 nike

我正在尝试在 Node.js 上使用 MongoDB + Mongoose 克隆类似 Reddit 的社区板 API。

我的示例 JSON 数据如下所示:

            {
"genre": "free",
"viewCount": 90,
"isDeleted": false,
"commentCount": 0,
"voteCount": 0,
"_comments": [],
"_vote": [],
"_id": "ObjectId",
"title": "blahblah",
"contents": "blah",
"createdAt": "2020-01-24T08:50:28.409Z",
"__v": 0,
"id": "5e2aafd4395bf593aa94b623"
},

为了解决这个问题,我简单地使用 .sort({ viewCount:-1,createdAt: -1 }) 进行排序。

但是,当我以这种方式排序时,最近创建的帖子将始终排在第一位,即使其他帖子具有更大的 viewCount 值...

我想到的下一件事是尝试按每天对帖子数据进行分组(即今天创建的所有帖子都分组在一起;昨天创建的所有帖子都分组在一起)。

分组后,也许我可以按viewCount对其余数据进行排序。

我相信使用aggregate的方法将是一种可能的解决方案,但我想知道是否有针对这个问题的最简单和最好的解决方案!

我想要得到的输出是这样的:

// viewcount in Descending Order
{ '2020-01-24':
{ post1: { viewcount: 999, contents: ...},
{ post2: { viewcount: 998, contents:... },
... } },
'2020-01-23':
{ post1: { viewcount: 999, contents: ...},
{ post2: { viewcount: 998, contents:... },
... },
'2020-01-22':
{ post1: { viewcount: 999, contents: ...},
{ post2: { viewcount: 998, contents:... },
... }, ...}

请帮帮我...

谢谢:)

最佳答案

此聚合提供了与您期望的输出类似的内容:

db.test.aggregate( [ 
{ $sort: { createdAt: -1, viewCount: -1} },
{ $group: { _id: "$createdAt", post: { $push: "$$ROOT" } } },
{ $project: { post: 1, date: "$_id", _id: 0 } }
] )

关于node.js - Mongoose/MongoDB 获取一天内浏览次数最多的文章分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59893890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com