Mongodb aggregation pipeline how to limit a group push

前端 未结 2 457
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 18:10

I am not able to limit the amount of pushed elements in a group function with aggregation pipeline. Is this possible? Small example:

Data:



        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 18:36

    You can achieve this by passing $slice operator directly at the $push.

      var pipeline = [{
        //I want to limit the data to a certain area
        $match: {
            loc: {
                $geoWithin: {
                    $box: [
                        [locBottomLeft.lng, locBottomLeft.lat],
                        [locUpperRight.lng, locUpperRight.lat]
                    ]
                }
            }
        }
    },
    // I just want to get the latest entries  
    {
        $sort: {
            submitted: -1
        }
    },
    // I group by name
    {
        $group: {
            _id: "$name",
            < --get name
            submitted: {
                $max: "$submitted"
            },
            < --get the latest date
            locs: {
                $push: {
                  $slice: 10
                }
            },
            < --push every loc into an array THIS SHOULD BE LIMITED TO AN AMOUNT 5 or 10
            preview: {
                $first: "$preview"
            }
        }
    },
    //Limit the query to at least 10 entries.
    {
        $limit: 10
    }
    ];
    
    

提交回复
热议问题