Array subset in aggregation framework pipeline

前端 未结 2 1715
情歌与酒
情歌与酒 2020-12-21 21:10

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(
          


        
相关标签:
2条回答
  • 2020-12-21 21:18

    As Stennie told, there is no $slice for an aggregation framework in 2.2 version of mongo, but in the upcomming 3.2 version of mongo they added it.

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

    And a couple of 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 讨论(0)
  • 2020-12-21 21:44

    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.

    0 讨论(0)
提交回复
热议问题