mongodb - 每个桶的顶级文档

标签 mongodb aggregation-framework

我想为 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/

相关文章:

node.js - 在 MongoDB 上,当我的回调在 "find"内时,如何限制查询?

java - MongoDB 一对多和多对一关系

python - 如何根据数组中的值对集合进行排序

mongodb - 当排序值相同时,Mongo 在 $skip 之后不会维持 $sort 顺序

javascript - 如何在mongodb中replaceRoot后进一步分组对象

javascript - 在javascript中循环遍历数组中的对象

php - 无法在 Ubuntu 16.04 上加载 PHP7 mongodb 驱动程序

mongodb - 条件总和 mongodb 聚合

python - 为nodejs安装mongoose模块时出错

javascript - 通过引用修改 Javascript 对象