Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

mongodb - Array subset in aggregation framework pipeline

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'}}}
)

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}

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}
)

But as it appears, I performed another $unwind pipeline. Is there a better solution to achieve what I am trying to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • your use of $skip and $limit in the aggregate() pipeline
  • manipulation of the results in your application code.
  • implementing the aggregation using Map/Reduce

There is an existing feature request in the MongoDB issue tracker that you can upvote/watch: SERVER-6074: Allow $slice operator in $project.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...