cha*_*hne 22 mongodb mongodb-query aggregation-framework
我无法使用聚合管道限制组函数中推送元素的数量.这可能吗?小例子:
数据:
[
{
"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"
}
]
Run Code Online (Sandbox Code Playgroud)
这是我的聚合管道:
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
}
];
Run Code Online (Sandbox Code Playgroud)
如何将locs数组限制为10任何其他大小?我想用的东西$each和$slice,但似乎并没有工作.
sty*_*ane 19
假设左下角坐标和右上角坐标分别为[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 }
])
Run Code Online (Sandbox Code Playgroud)
从 开始Mongo 5.2,这是新$topN聚合累加器的完美用例:
// { submitted: ISODate("2021-12-05"), group: "group1", value: "plop" }
// { submitted: ISODate("2021-12-07"), group: "group2", value: "smthg" }
// { submitted: ISODate("2021-12-06"), group: "group1", value: "world" }
// { submitted: ISODate("2021-12-12"), group: "group1", value: "hello" }
db.collection.aggregate([
{ $group: {
_id: "$group",
top: { $topN: { n: 2, sortBy: { submitted: -1 }, output: "$value" } }
}}
])
// { _id: "group1", top: [ "hello", "world" ] }
// { _id: "group2", top: [ "smthg" ] }
Run Code Online (Sandbox Code Playgroud)
这适用于$topN以下组累积:
n: 2) 元素sortBy: { submitted: -1 }(按时间倒序)value( output: "$value")| 归档时间: |
|
| 查看次数: |
5083 次 |
| 最近记录: |