Mongodb 每个存储桶的顶级文档

Mongodb 每个存储桶的顶级文档,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我想为N个类别中的每一个获得N个最高字段的文档。例如,过去3个月中,每个月得分最高的3个职位。所以每个月都会有3篇文章在那个月“获胜” 以下是我的工作到目前为止得到的简化 // simplified db.posts.aggregate([ {$bucket: { groupBy: "$createdAt", boundaries: [ ISODate('2019-06-01'), ISODate('2019-07-01'),

我想为N个类别中的每一个获得N个最高
字段的文档。例如,过去3个月中,每个月得分最高的3个职位。所以每个月都会有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操作符,但出现了一个错误(如下所示)

您尝试使用的专用于更新操作。要获得前N个帖子,您需要运行,然后运行和以获得有序数组。作为您可以使用的最后一步,请尝试:

  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 }
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 ] } } }
])