我想为 N 个类别中的每个类别获取具有 N 个最高 字段
的文档。例如,过去 3 个月中每个月的 3 个最高 score
的帖子。所以每个月都会有 3 个帖子在那个月“获胜”。
这是到目前为止我的工作得到的简化。
// simplified
db.posts.aggregate([
{$bucket: {
groupBy: "$createdAt",
boundaries: [
ISODate('2019-06-01'),
ISODate('2019-07-01'),
ISODate('2019-08-01')
],
default: "Other",
output: {
posts: {
$push: {
// ===
// This gets all the posts, bucketed by month
score: '$score',
title: '$title'
// ===
}
}
}
}},
{$match: {_id: {$ne: "Other"}}}
])
我试图在 //===
之间使用 $slice 运算符,但出现错误(如下)。
postResults: {
$each: [{
score: '$score',
title: '$title'
}],
$sort: {score: -1},
$slice: 2
}
An object representing an expression must have exactly one field: { $each: [ { score: \"$score\", title: \"$title\" } ], $sort: { baseScore: -1.0 }, $slice: 2.0 }
最佳答案
$slice您尝试使用专用于更新操作。要获得前 N 个帖子,您需要运行 $unwind , 然后 $sort和 $group获取有序数组。作为最后一步,您可以使用 $slice (aggregation) , 尝试:
db.posts.aggregate([
{$bucket: {
groupBy: "$createdAt",
boundaries: [
ISODate('2019-06-01'),
ISODate('2019-07-08'),
ISODate('2019-08-01')
],
default: "Other",
output: {
posts: {
$push: {
score: '$score',
title: '$title'
}
}
}
}},
{ $match: {_id: {$ne: "Other"}}},
{ $unwind: "$posts" },
{ $sort: { "posts.score": -1 } },
{ $group: { _id: "$_id", posts: { $push: { "score": "$posts.score", "title": "$posts.title" } } } },
{ $project: { _id: 1, posts: { $slice: [ "$posts", 3 ] } } }
])
关于mongodb - 每个桶的顶级文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56960040/