【问题标题】:Create MongoDb View from an aggregation with current date filter使用当前日期过滤器从聚合创建 MongoDb 视图
【发布时间】:2020-03-08 11:51:32
【问题描述】:

我想创建一个视图和聚合,它使用 currentdate 应用日期过滤器。 在下面给出的示例中,我使用当前日期作为字符串并且工作正常,但我需要自动更新这些日期。

{
  $and: [{
      'promotionRange.start': {$lte:  ISODate('2019-11-12')}
      },
      {
      "promotionRange.end": {"$gte": ISODate('2019-11-12')}
      }
  ]
}

我需要类似下面的代码

{
  $and: [{
      'promotionRange.start': {$lte:  $currentDate}
      },
      {
      "promotionRange.end": {"$gte": $currentDate}
      }
  ]
}

这不起作用。并且 new Date() 也不起作用。

在聚合查询中使用当前日期有什么技巧吗?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    我认为在 start 和 end 日期中使用相同的日期是不正确的,如果您想从今天开始过滤到当前日期/时间,您可以检索当前日期为字符串,使用new Date().toISOString().slice(0,10) 作为start 日期,对于end 日期使用ISODate,不带参数:

    const startDate = new Date().toISOString().slice(0,10); // "2019-11-13"
    
    ...
    
    
    {
      $and: [{
          'promotionRange.start': {$lte:  ISODate(startDate)} // 2019-11-13T00:00:00Z
          },
          {
          'promotionRange.end': {$gte: ISODate()}
          }
      ]
    }
    

    【讨论】:

    • 这段代码在哪里写?进入 MongoDB 指南针聚合面板?这是行不通的?我是 mongo db 的新手?那个 const 部分不起作用!
    猜你喜欢
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2020-10-27
    • 2020-03-29
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多