自定义mongodb $限制聚合

发布于 2025-02-11 19:19:46 字数 558 浏览 1 评论 0原文

我需要在汇总中使用MongoDB的$限制,但我想添加文档限制条件。但是我不知道这是可能的。

示例:

db.collection.find()

{"type": "one"}
{"type": "two"}
{"type": "one"}
{"type": "three"}
{"type": "one"}
{"type": "three"}

db.Collection.Aggregation([[ ... ])

结果我需要聚集:

{"type": "one"}
{"type": "two"}
{"type": "one"}
{"type": "three"}
{"type": "three"}

在这种情况下,我需要按类型限制文档。我最多想要同一类型的2个文档。我该怎么做?

提前致谢 :)

I need to use mongodb's $limit in the aggregation but I wanted to add a document limiting condition. But I don't know if this is possible.

Example:

db.collection.find()

{"type": "one"}
{"type": "two"}
{"type": "one"}
{"type": "three"}
{"type": "one"}
{"type": "three"}

db.collection.aggregation([
...
])

Result I need the aggregation:

{"type": "one"}
{"type": "two"}
{"type": "one"}
{"type": "three"}
{"type": "three"}

In this case I need to limit the documents by type. And I wanted at most 2 documents of the same type. How could I do this?

Thanks in advance :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅黛梨妆こ 2025-02-18 19:19:46

这里是一种方法。而不是使用$ limit,将文档按其中类型分组,然后将分组的文档推入数组中。然后将该数组切成一个仅包含两个元素。最终放松阵列,然后返回结果:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$type",
      "docs": {
        "$push": "$ROOT"
      }
    }
  },
  {
    "$project": {
      docs: {
        "$slice": [
          "$docs",
          2
        ]
      },
      _id: 0,
    },
  },
  {
    "$unwind": "$docs"
  },
  {
    "$replaceRoot": {
      "newRoot": "$docs"
    }
  }
])

这是游乐场[ link ] 1

Here, is one way of doing it. Instead of using $limit, group the documents by there type, and push the grouped docs in an array. Then slice that array to contain only two elements. Finally unwind the array, and return the results like this:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$type",
      "docs": {
        "$push": "$ROOT"
      }
    }
  },
  {
    "$project": {
      docs: {
        "$slice": [
          "$docs",
          2
        ]
      },
      _id: 0,
    },
  },
  {
    "$unwind": "$docs"
  },
  {
    "$replaceRoot": {
      "newRoot": "$docs"
    }
  }
])

Here's the playground [link]1

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文