【问题标题】:Comparing Three Dates to Get Latest in MongoDB比较三个日期以获取 MongoDB 中的最新信息
【发布时间】:2018-10-19 13:10:42
【问题描述】:

在我的 Mongo 集合中,我需要比较三个日期,并找到最近的一个。我想知道是否有一种速记或原生 MongoDB 方式来执行此操作?

在原版 JS 中比较两个日期时,我可以这样:

let compareDates = (date1, date2) => {
   if (date1>date2) return ("Date1 > Date2");
   else if (date1<date2) return ("Date2 > Date1");
   else return ("Date1 = Date2"); 
  }

console.log(compare_dates(new Date('11/14/2018 00:00'), new Date('11/14/2018 00:00')));
console.log(compare_dates(new Date('11/14/2018 00:01'), new Date('11/14/2018 00:00')));
console.log(compare_dates(new Date('11/14/2018 00:00'), new Date('11/14/2018 00:01')));

...但这会因为三个日期而变得很长。有没有更短的方法来比较三个日期并返回最近的日期?

让我们假设一个这样的简化模型:

{
    _id: '123',
    date1: {
      type: Date,
    },
    date2: {
      type: Date,
    },
    date3: {
      type: Date,
    }
}

【问题讨论】:

  • 你能展示你的模型吗?

标签: javascript mongodb date


【解决方案1】:

假设您的模型如下所示:

{
    date1: ISODate("1990-01-01T00:00:00Z"),
    date2: ISODate("1980-01-01T00:00:00Z"),
    date3: ISODate("1970-01-01T00:00:00Z")
}

您可以简单地使用$max 来获取最近的日期:

db.collection.aggregate([
    {
        $project: {
            recentDate: { $max: [ "$date1", "$date2", "$date3" ] }
        }
    }
])

【讨论】:

  • 太棒了! $max 在这里听起来像是完美的解决方案。谢谢,@mickl!
【解决方案2】:

只是为了添加一些 POJS 解决方案,Math.max 可以工作,但会返回一个时间值。或者,将它们排序在一个数组中并获取最后一个:

var dates = [
  new Date('2018-01-01'),
  new Date('2018-01-03'),
  new Date('2018-01-02') 
];

// Returns a new Date
console.log(new Date(Math.max(...dates)));

// Returns one of the dates, sorts and shortens the array
console.log(dates.sort((a,b)=>a-b).pop()); 

// Returns a reference to one of the dates, sorts but doesn't shorten the array
console.log(dates.sort((a,b)=>a-b).slice(-1)[0]);



  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    相关资源
    最近更新 更多