Mongodb聚合限制单个字段值出现次数

gijlo24d  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(187)

我有一个包含分类和时间戳的博客文章列表。现在,如果我想按时间顺序排列它们,但限制每个分类的出现次数,比如说,* 每个分类只有3篇文章 *,常规的$group似乎不是正确的方法。topN也是如此,因为它按分类对这些文章进行了分组,但我失去了时间顺序列表。

ovfsdjhp

ovfsdjhp1#

您仍然可以将"$group""$topN"一起使用,然后,例如,接着使用另一个"$group"、排序、"$unwind""$replaceWith"
注意:这将给予最早的帖子。如果你想要最新的帖子,你可以调整排序顺序。

db.blogPosts.aggregate([
  { // get max 3 items from category
    // sorted by timestamp
    "$group": {
      "_id": "$category",
      "postsTop3": {
        "$topN": {
          "n": 3,
          "sortBy": {"timestamp": 1},
          "output": "$$ROOT"
        }
      }
    }
  },
  { // aggregate all top3's
    "$group": {
      "_id": null,
      "posts": {"$push": "$postsTop3"}
    }
  },
  { // sort them all by timestamp
    "$set": {
      "posts": {
        "$sortArray": {
          "input": {
            "$reduce": {
              "input": "$posts",
              "initialValue": [],
              "in": {
                "$concatArrays": ["$$value", "$$this"]
              }
            }
          },
          "sortBy": {"timestamp": 1}
        }
      }
    }
  },
  {"$unwind": "$posts"},
  {"$replaceWith": "$posts"}
])

试试看mongoplayground.net

相关问题