每个存储区的主要文档

时间:2019-07-09 20:24:21

标签: mongodb aggregation-framework

我想获得N个类别中每个类别的N个最高field个文档。例如,过去3个月中每个月的score最高的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运算符,但出现错误(如下)。

  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 }

1 个答案:

答案 0 :(得分:1)

您尝试使用的

$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 ] } } }
])
相关问题