从nodejs查询MongoDB中的日期范围

时间:2017-03-20 09:29:01

标签: node.js mongodb date-range

我想让所有用户都在指定的日期范围内, 我的数据库结构如下所示:

{
    _id : ObjectId("58b545d4b57eeb2cc456248a"),
    "attendance" : [ 
        {
            "2017-03-16" : ["58c108b9ebd9ae24dca81634"],
            "2017-03-17" : ["58c108b9ebd9ae24dca81634"],
            "2017-03-18" : ["58c108b9ebd9ae24dca81634"],
            "2017-03-19" : ["58c108b9ebd9ae24dca81634"],
            "2017-03-20" : ["58c108b9ebd9ae24dca81634","58c108b9ebd9ae24dca81635"]
        }, 
        {
            "2017-03-17" : ["58c108b9ebd9ae24dca81634"],
            "2017-03-18" : ["58c108b9ebd9ae24dca81634"],
            "2017-03-19" : ["58c108b9ebd9ae24dca81634"],
            "2017-03-20" : ["58c108b9ebd9ae24dca81634","58c108b9ebd9ae24dca81635"]
        }
    ]
    .......
}

并查询它:

routes.find({_id: ObjectId("58b545d4b57eeb2cc456248a"), $or:[{'attendance[0]' : {$gte: '2017-03-17' }}, {'attendance[1]': {$gte: '2017-03-17'}}]})

但它没有取得任何结果。

2 个答案:

答案 0 :(得分:3)

您的日期似乎保存在(字段名)中;但MongoDB仅用于查询字段 values 中保存的数据。我建议你将数据重组为以下内容:

routes.aggregate([
    {$match: { _id: ObjectId("58b545d4b57eeb2cc456248a")}},
    {$match: {"attendance.dateitems.when" : {$gt: ISODate("2017-03-17")}}}
})

使用这种数据结构,您可以查询以获得所需的输出,例如:

+

以下是我在重组过程中改变的一些要点:

  1. 而不是字符串,每个ObjectId引用都是真正的ObjectID type;这将允许有效的比较和查找。
  2. 使用ISODate格式,每个日期都使用标准化的Date data type,而不是字符串;这样可以进行有效的比较,例如$ gt。
  3. 考勤数据已扩展为一系列 dateitem 对象,每个对象都有一个日期字段和一个引用对象的字段(我猜测那些是ids)参加的人);这样,每个数据值都存储为field value - 而不是字段名。

答案 1 :(得分:-1)

在node.js中,我们可以通过新的Date()查询ISODate来查找日期范围数据

db.collectionName.find({ 
   'updatedAt': {
          $gte: new Date('2019-04-19T14:16:04.065Z'),
          $lte: new Date('2019-04-19T14:16:04.070Z')
        }})