【问题标题】:How to find a sort/query in a collection with the most recent time如何在最近时间的集合中查找排序/查询
【发布时间】:2014-07-20 11:08:07
【问题描述】:

我有一个名为 sceanarios 的集合,其中包含不同的两个 gmt 时间 createDateupdateDate。我想根据最近的时间查询/排序文档,无论最近的时间是在 createDate 还是 updateDate。

【问题讨论】:

  • 我猜如果有 updateDate 它总是比 createDate 更新?那你为什么不把 updateDate = createDate 添加到所有尚未更新的文档中并始终使用它呢?我认为这比在 find 和 sort 中找到最小值要容易得多。

标签: mongodb mongoose


【解决方案1】:

您可以使用聚合框架来做到这一点,如下所示:

db.yourColl.aggregate(
                 {$project:{ 
                     greaterDate:
                                {$cond:[{$gt:["$createDate","$updateDate"]},
                                 "$createDate",
                                 "$updateDate"]
                                }
                           }
                 },
                 {$sort:{ greaterDate:-1}})

但是,您需要枚举所有要保留在 $project 部分中的字段

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2018-03-18
    • 2015-02-08
    • 2015-07-26
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多