MongoDB聚合管道:获取最后N条记录
以下是我在MongoDB聚合管道中的当前代码:MongoDB聚合管道:获取最后N条记录,mongodb,aggregation-framework,Mongodb,Aggregation Framework,以下是我在MongoDB聚合管道中的当前代码: db.mydatabase.aggregate([ { "$project" : { "mpmonth":{"$last":"$month"}, } } ]) 目前,此代码只允许获取最近一个月(例如7月),我希望获取之前6个月(例如1月)的记录 有没有办法获取最近N个月的记录?我该怎么做 更新: 感谢@And
db.mydatabase.aggregate([
{
"$project" :
{
"mpmonth":{"$last":"$month"},
}
}
])
目前,此代码只允许获取最近一个月(例如7月),我希望获取之前6个月(例如1月)的记录
有没有办法获取最近N个月的记录?我该怎么做
更新:
感谢@AndrewShmig的建议,以下是我解决问题的方法:
db.mydatabase.aggregate([
{
"$sort" : {
"seq" : -1
}
},
{
"$skip" : 6
}
])
在这里,我添加了另一列名为:seq的数据,I$按降序排序记录,然后$跳过前6条记录,现在第一条记录将显示“$Month”=“Jan”。最后,在我的JavaScript中,我选择了第一条记录:
$group": {
"mpmonth":{"$first":"$mpmonth"}
}
使用运算符的替代解决方案
db.mydatabase.aggregate([
{
"$sort": {
"seq": -1
}
},
{
$group: {
_id: null,
"month": {
"$push": "$month"
}
}
},
{
$project: {
mpmonth: {
$arrayElemAt: ["$month", 6] //N-th element, being -1 the last element
}
}
}
])
排序
+限制
?@AndrewShmig您能分享一些例子吗?谢谢@安德烈:我想美元限额会给我几个月的回报。我试着从上个月的第N个月取回。