A subset of the array in the aggregation structure pipeline

In the previous question, I wanted to get the counter of the received groups using operations with pipelines. 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, knowing the score, I would like to display the results on the page, so I only need a subset of data . My initial thought was using $slice in data in the $project pipeline, for example:

 ... {$project: {data : { $slice: [20,20] }, total: 1} 

But it turns out that $slice not a valid operation for $project . I tried a workaround:

 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 turned out, I executed another $unwind pipeline. Is there a better solution to achieve what I'm trying to do?

+1
source share
2 answers

Unfortunately, at present (as in MongoDB 2.2) there is no Aggregation Operator for $slice or take a subset of an array.

You need to use a workaround, for example:

  • using $skip and $limit in the aggregate() pipeline
  • manipulating results in your application code.
  • aggregation implementation using Map / Reduce

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

+3
source

As Stenny said, there is no $slice for the aggregation structure in version 2.2 of the mongo version , but in the updated version 3.2 mongo they added it.

So now you can use $ slice in aggregation . To return elements from the beginning or end of an array: { $slice: [ <array>, <n> ] } To return elements from a specified position in an array: { $slice: [ <array>, <position>, <n> ] } .

And a few examples from the Mongo page:

 { $slice: [ [ 1, 2, 3 ], 1, 1 ] } // [ 2 ] { $slice: [ [ 1, 2, 3 ], -2 ] } // [ 2, 3 ] { $slice: [ [ 1, 2, 3 ], 15, 2 ] } // [ ] { $slice: [ [ 1, 2, 3 ], -15, 2 ] } // [ 1, 2 ] 
0
source

All Articles