【问题标题】:MongoDB Aggeregation Pipeline: Get last N-th recordMongoDB 聚合管道:获取最后第 N 条记录
【发布时间】:2020-07-02 12:48:42
【问题描述】:

这是我当前在 MongoDB 聚合管道中的代码:

db.mydatabase.aggregate([
  {
    "$project" : 
      {
        "mpmonth":{"$last":"$month"},
      }
   }
])

目前,此代码只允许获取最近的月份(例如 7 月),我想获取之前 6 个月的记录(例如 1 月)。

有没有办法获取最后 N 个月的记录,我该怎么做?

更新:

感谢@AndrewShmig 的建议,这是我解决问题的方法:

db.mydatabase.aggregate([
  {
    "$sort" : {
      "seq" : -1
    }
  },
  {
    "$skip" : 6
  }
])

在这里,我添加了另一列名为:seq的数据,我将记录按降序排序,然后$跳过前6条记录,现在第一条记录将显示“$Month”=“Jan” .最后,在我的 JavaScript 中,我选择了第一条记录:

$group": { 
        
        "mpmonth":{"$first":"$mpmonth"}
}

【问题讨论】:

  • sort + limit ?
  • @AndrewShmig 你能分享一些例子吗?谢谢!
  • @AndrewShmig 我认为 $limit 会给我 N 个月的回报。我试图从上个月的第 N 个月回来。

标签: mongodb aggregation-framework


【解决方案1】:

使用$arrayElemAt 运算符的替代解决方案。

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
      }
    }
  }
])

MongoPlayground

【讨论】:

    猜你喜欢
    • 2011-05-24
    • 2016-07-15
    • 2018-11-23
    • 1970-01-01
    • 2021-07-18
    • 2013-12-31
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多