【问题标题】:Get the latest year in MongoDB获取 MongoDB 的最新年份
【发布时间】:2021-12-23 12:20:48
【问题描述】:

在处理一个项目时,我遇到了一个我似乎无法在任何地方找到解决方案的问题。

我正在为 MongoDB 使用 NoSQLBooster,我需要获取数据中最近一年的数据。 我不想以降序方式对其进行排序(这样做会显示所有值,并且我可以看到 2018 年是最新的),但我希望它只显示数字 2018。 有谁知道我该怎么做?

提前谢谢你!

【问题讨论】:

    标签: json mongodb mongodb-query


    【解决方案1】:

    您可以使用$group (aggregation)

    db.aggregate(
      [
        {
          $group :
            {
              _id : null,
              maxYear: { $max: "$yearField" }
            }
         }
       ]
     )
    

    【讨论】:

      【解决方案2】:

      这很快:

      var x=  db.find({},{_id:1}).sort(_id:-1).limit(1)
       x._id.getTimestamp()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-02
        • 1970-01-01
        • 1970-01-01
        • 2014-05-12
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多