自定义mongodb $限制聚合
我需要在汇总中使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里是一种方法。而不是使用
$ limit
,将文档按其中类型分组,然后将分组的文档推入数组中。然后将该数组切成一个仅包含两个元素。最终放松阵列,然后返回结果:这是游乐场[ 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:Here's the playground [link]1