【发布时间】:2020-02-13 14:53:26
【问题描述】:
在 mongodb 中,如果我们想获取小组赛的第一个或最后一个文档,那么 FIRST 和 LAST 运算符会有所帮助。我想根据 _id:"$department" 对集合进行分组,并获取 LAST 文档和 LAST-1 文档。有什么办法可以做到这一点。
【问题讨论】:
标签: mongodb
在 mongodb 中,如果我们想获取小组赛的第一个或最后一个文档,那么 FIRST 和 LAST 运算符会有所帮助。我想根据 _id:"$department" 对集合进行分组,并获取 LAST 文档和 LAST-1 文档。有什么办法可以做到这一点。
【问题讨论】:
标签: mongodb
假设你有这个收藏:
[
{ department: "HR", employees: 20 },
{ department: "Finance", employees: 30 },
{ department: "Sales", employees: 5 },
{ department: "IT", employees: 50 }
]
然后你可以运行这个聚合:
db.collection.aggregate([
{ $sort: { department: 1 } },
{
$group: {
_id: null,
employees: { $sum: "$employees" },
all_departments: { $push: "$department" }
}
},
{
$set: {
last_departments: {
$concatArrays: [
[{ $arrayElemAt: ["$all_departments", -1] }],
[{ $arrayElemAt: ["$all_departments", -2] }]
]
}
}
}
])
更新
$slice 更短:
db.collection.aggregate([
{ $sort: { department: 1 } },
{
$group: {
_id: null,
employees: { $sum: "$employees" },
all_departments: { $push: "$department" }
}
},
{ $set: { last_departments: { $slice: ["$all_departments", -2] } } }
])
【讨论】: