MongoDB的聚合管道如何限制一组推MongoDB的聚合管道如何限制一组推(Mongodb agg

2019-05-12 04:19发布

我不能限制具有聚合管道一组函数推元素的量。 这可能吗? 小例子:

数据:

[
    {
        "submitted": date,
        "loc": {
            "lng": 13.739251,
            "lat": 51.049893
        },
        "name": "first",
        "preview": "my first"
    },
    {
        "submitted": date,
        "loc": {
            "lng": 13.639241,
            "lat": 51.149883
        },
        "name": "second",
        "preview": "my second"
    },
    {
        "submitted": date,
        "loc": {
            "lng": 13.715422,
            "lat": 51.056384
        },
        "name": "nearpoint2",
        "preview": "my nearpoint2"
    }
]

这里是我的聚集管道:

  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: "$loc"
        },
        < --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
}
];

我怎样才能限制locs阵列10或任何其他大小? 我想用的东西$each$slice ,但似乎并没有工作。

Answer 1:

假设左下坐标和右上坐标分别为[0, 0][100, 100] 从MongoDB的3.2可以使用$slice运算符来返回数组的一个子集,这是你想要的。

db.collection.aggregate([
    { "$match": { 
        "loc": { 
            "$geoWithin":  { 
                "$box": [ 
                    [0, 0], 
                    [100, 100]
                ]
            }
        }}
    }},
    { "$group": { 
        "_id": "$name",
        "submitted": { "$max": "$submitted" }, 
        "preview": { "$first": "$preview" }
        "locs": { "$push": "$loc" }
    }}, 
    { "$project": { 
        "locs": { "$slice": [ "$locs", 5 ] },
        "preview": 1,
        "submitted": 1
    }},
    { "$limit": 10 }
])


文章来源: Mongodb aggregation pipeline how to limit a group push