【问题标题】:How to compare the current time with the existing date fields in mongodb?如何将当前时间与 mongodb 中的现有日期字段进行比较?
【发布时间】:2016-06-15 06:25:42
【问题描述】:

这是我的架构

{
    "from": {type: Date, required: true},
    "to": {type: Date, required: true},
    "slotname": {type: String, required: true},
    "createdAt": {type: Date, default: Date.now},
    "modifiedAt": {type: Date, default: Date.now},
    "isDeleted": {type: Boolean, default: false}
}

使用此架构,我总共创建了 10 条记录。对于这 10 条记录,槽名是 "slot1","slot2"..."slot10"

fromto 时间分别为 9-11, 11-1, 2-4, 4-6, 6-9, 9-11, 11-1, 2-4, 4-6, 6-9

现在我需要将这些与current time 进行比较。

假设如果当前时间是11,它应该返回由fromto时间组成的文档为2-4, 4-6, 6-9 and 9-11

我怎样才能做到这一点?

【问题讨论】:

  • 您能否向我们展示您迄今为止为实现这一目标所做的努力?
  • @SambitD 实际上我需要根据时间向客户展示插槽。 from 和 **to ** 是包含完整日期格式的两个字段。

标签: node.js mongodb express mongodb-query


【解决方案1】:

当您创建任何插槽时,您不应将日期保留为 from 和 to。这些不是特定的一天,对吧!

您可以将槽的小时值输入为整数。让我们占据第一个位置。在那里你可以从 as 2 和 to 插入。

那么查询会是这样的

var tStamp = new Date();
var hr = tStamp.getHour();
query = {
        from: {
            $lte: hr
        }, 
        to: {
            $lte: hr
        }
    };
yourCollection.find(query).toArray(callbackFn);

$lte-mongodb

【讨论】:

  • 您不应该将 slot 存储为字符串,因为$lte 不适用于字符串值,因此请将小时数仅保留为整数。
猜你喜欢
  • 2018-04-04
  • 2015-09-01
  • 2011-11-14
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 2022-09-27
  • 2017-05-04
  • 2022-01-16
相关资源
最近更新 更多