我如何投影5个计数并在MongoDB中概括其余的计数?
我有以下文档:
_id: "Team 1"
count: 1200
_id: "Team 2"
count: 1170
_id: "Team 3"
count: 1006
_id: "Team 4"
count: 932
_id: "Team 5"
count: 931
_id: "Team 6"
count: 899
_id: "Team 7"
count: 895
列表已经对其进行整理,并且所有内容都需要根据计数将其投影为前5名的数组,然后将其余的应求和为“其他”。如果可能的话,我还要添加列表中每个元素的百分比由全部计数构成。像这样:
[
{"name":"Team 1", "count":1200, "percent":25},
{"name":"Team 2", "count":1170,"percent":15},
{"name":"Team 3", "count":1006,"percent":10},
{"name":"Team 4", "count":932,"percent":5},
{"name":"Team 5", "count":931,"percent":5},
{"name":"Other", "count":1794, "percent":40}]
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查询
$ setWindowfields
进行排序,并通过null
与3个累加器$ map
将计数与5个顶级文档的总和分开,以获取(将鼠标放在每个阶段的末端,以查看阶段进出)
Query
$setWindowFields
to sort and add the sort-rank to each documentnull
with 3 accumulators$map
to divide the counts with the total sum for the 5 top documents, to get the percentage alsoPlaymongo (put the mouse at the end of each stage to see the stage in and out)
使用
$ facet
进行此操作的另一种方法,因为$ setWindowfields
仅与mongodb v5或更高版本一起使用mongoplayground
another way to do it using
$facet
since$setWindowFields
only works with mongodb v5 or latermongoPlayground
如果您的MongoDB版本5.0或更高版本,则可以使用
$ setWindowfields
在@takis中的好答案。否则,您可以group
,$ slice
和$ redion
您的答案方式:$ sort
顶部和组的最高计数将它们全部放入一个数组中,称为ash all
和$ sum
up。$ slice
所有
数组仅保留顶部N。$ redaim
the the the the the top n可以将它们总结。其他
添加到带有Countsum-sum(topn)
$ untind
和格式<代码> <代码> ) 的顶部N数组中mongoplayground.net/p/ckttf9iblt0“ rel =“ nofollow noreferrer”>游乐场示例
If you have mongoDB version 5.0 or higher you can use
$setWindowFields
like in @Takis nice answer. Otherwise, you cangroup
,$slice
and$reduce
your way to the answer:$sort
to have the highest count on top and group to put them all in one array calledall
and to$sum
up.$slice
theall
array to keep only the top N.$reduce
the top N to sum them up.others
to the top N array with countsum-sum(topN)
$unwind
and formatPlayground example