本文介绍了分组时Mongo aggregation限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合,它按字段类型"进行聚合和分组.最终结果应该是每种类型最多五个文档.但是如果我在分组之前限制只有五个第一个文档将被分组.如果我限制在组之后,前五种类型将返回.

I have a collection which im aggregating and grouping by the field "type". The final result should be just maximum of five documents in each type. But if i limit before group only five first docs will be grouped. if i limit after the group the first five types will return.

有没有办法在不为每种类型执行 find() 的情况下做到这一点,限制为 5 并合并所有结果?

is there a way to do this without doing find() for each type , limiting to 5 and merging all the results ?

推荐答案

如果您可以使用 C#(根据我对 mongodb 的快速 google-search),您可以使用具有"ResultSelector-Function",像这样:

If you can use C# (which according to my quick google-search about mongodb you do), you can do this with one of the GroupBy's which have an "ResultSelector-Function", like this:

var groups = Enumerable.Range(0, 1000).
                GroupBy(
                        x => x/10, 
                        (key, elements) => new  { Key = key, Elements = elements.Take(5) }
                       );

关于这段代码的速度 - 我相信在结果选择器被实例化之前已经完全构建了组 - 因此对输入序列进行自定义 foreach 并手动构建组可能会更快(如果您能以某种方式确定何时完成)

About the speed of this code - I believe the group is completely build before the result-selector is instantiated - so a custom foreach over the input sequence and building the groups by hand might be faster (if you can somehow determine when you are done)

PS:再想一想 - 我怀疑我的答案是你想要的.我查看了 mongo-DB 文档,map"结合合适的reduce"函数可能正是您想要的.

P.S.: On second thought - I doubt my answer is the one you want. I had a look at the mongo-DB documentation, and "map" in combination with a suitable "reduce" function might be exactly what you want.

这篇关于分组时Mongo aggregation限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 12:24