问题描述
在上一个问题中,我想获得结果的计数组使用管道操作.如建议的那样,我使用了以下内容:
In a previous question I wanted to obtain a count of the resulting groups using pipeline operations. As suggested, I used the following:
db.test.aggregate(
{$unwind: '$tags'},
{$group:{_id: '$tags', count:{$sum:1}}},
{$project:{tmp:{tag:'$_id', count:'$count'}}},
{$group:{_id:null, total:{$sum:1}, data:{$addToSet:'$tmp'}}}
)
现在知道计数了,我想按页面显示结果,所以我只需要data
的子集.我最初的想法是在$project
管道中的data
上使用$slice
,例如:
Now having known the count, I would like to display the results by page so I would only need a subset of data
. My initial thought would be using $slice
on data
within a $project
pipeline like:
...
{$project: {data : { $slice: [20,20] }, total: 1}
但是$slice
似乎不是$project
的有效操作.我尝试通过以下方法解决此问题:
But it appears that $slice
is not a valid operation for $project
. I tried a workaround by doing:
db.test.aggregate(
{$unwind: '$tags'},
{$group:{_id: '$tags', count:{$sum:1}}},
{$project:{tmp:{tag:'$_id', count:'$count'}}},
{$group:{_id:null, total:{$sum:1}, data:{$addToSet:'$tmp'}}},
{$unwind: '$data'},
{$skip: 20},
{$limit: 20}
)
但是看起来,我执行了另一个$unwind
管道.是否有更好的解决方案来实现我想要做的事情?
But as it appears, I performed another $unwind
pipeline. Is there a better solution to achieve what I am trying to do?
推荐答案
不幸的是,目前(在MongoDB 2.2上)没有聚合框架运算符$slice
或获取数组的子集.
Unfortunately there is currently (as at MongoDB 2.2) no Aggregation Framework operator to $slice
or take a subset of an array.
您将需要使用以下解决方法:
You will need to use a workaround such as:
- 您在
aggregate()
管道中使用$skip
和$limit
- 在应用程序代码中处理结果.
- 使用 Map/Reduce 实施汇总
- your use of
$skip
and$limit
in theaggregate()
pipeline - manipulation of the results in your application code.
- implementing the aggregation using Map/Reduce
MongoDB问题跟踪器中有一个现有的功能请求,您可以对其进行投票/观看: SERVER- 6074:在$ project 中允许$ slice运算符.
There is an existing feature request in the MongoDB issue tracker that you can upvote/watch: SERVER-6074: Allow $slice operator in $project.
这篇关于聚合框架管道中的数组子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!