MongoDB聚合管道如何限制组推送 [英] Mongodb aggregation pipeline how to limit a group push
本文介绍了MongoDB聚合管道如何限制组推送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法使用聚合管道来限制组函数中推送的元素的数量.这可能吗?小例子:
I am not able to limit the amount of pushed elements in a group function with aggregation pipeline. Is this possible? Small example:
数据:
[
{
"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
进行操作,但这似乎不起作用.
How can I limit the locs
array to 10
or any other size? I tried something with $each
and $slice
but that does not seem to work.
推荐答案
假定左下角坐标和右上角坐标分别为[0, 0]
和[100, 100]
.在MongoDB 3.2中,您可以使用 $slice
运算符以返回所需的数组子集.
Suppose the bottom left coordinates and the upper right coordinates are respectively [0, 0]
and [100, 100]
. From MongoDB 3.2 you can use the $slice
operator to return a subset of an array which is what you want.
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聚合管道如何限制组推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文