gpt4 book ai didi

Mongodb聚合管道如何限制组推送

转载 作者:IT老高 更新时间:2023-10-28 13:05:37 24 4
gpt4 key购买 nike

我无法使用聚合管道限制组函数中推送元素的数量。这可能吗?小例子:

数据:

[
{
"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 尝试了一些东西,但这似乎不起作用。

最佳答案

假设左下坐标和右上坐标分别为[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聚合管道如何限制组推送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com