在Mongoose中进行范围查询,包括小时/日/月/年

时间:2013-06-09 10:28:50

标签: mongodb mongoose date-range range-query nosql

试图找出如何做到这一点。基本上我想按提交的小时/日/月/年排序。

每个submission都有一个created字段,其中包含"created" : ISODate("2013-03-11T01:49:09.421Z")形式的Mongoose Date对象。我是否需要在find()条件下与此进行比较?

这是我当前的查询(我将其包装为分页目的FWIW,所以只需忽略该部分):

  getSubmissionCount({}, function(count) {

  // Sort by the range
    switch (range) {
      case 'today':
        range = now.getTime();
      case 'week':
        range = now.getTime() - 7;
      case 'month':
        range = now.getTime() - 31; // TODO: make this find the current month and # of   days in it
      case 'year':
        range = now.getTime() - 365;
      case 'default':
        range = now.getTime();
    }

    Submission.find({
      }).skip(skip)
         .sort('score', 'descending')
         .sort('created', 'descending')
         .limit(limit)
         .execFind(function(err, submissions) {
            if (err) {
          callback(err);
        }

        if (submissions) {
          callback(null, submissions, count);
        }
    });
  });

有人可以帮我解决这个问题吗?使用当前代码,它只是给我所有提交,无论时间范围,所以我显然没有做正确的事情

1 个答案:

答案 0 :(得分:15)

我认为,您正在MongoDB中查找$lt(小于)和$gt(大于)运算符。 通过使用上述运算符,可以根据时间查询结果。

我在下面添加了可能的解决方案。

var d = new Date(),
hour = d.getHours(),
min = d.getMinutes(),
month = d.getMonth(),
year = d.getFullYear(),
sec = d.getSeconds(),
day = d.getDate();


Submission.find({
  /* First Case: Hour */
  created: { $lt: new Date(), $gt: new Date(year+','+month+','+day+','+hour+','+min+','+sec) } // Get results from start of current hour to current time.
  /* Second Case: Day */
  created: { $lt: new Date(), $gt: new Date(year+','+month+','+day) } // Get results from start of current day to current time.
  /* Third Case: Month */
  created: { $lt: new Date(), $gt: new Date(year+','+month) } // Get results from start of current month to current time.
  /* Fourth Case: Year */
  created: { $lt: new Date(), $gt: new Date(year) } // Get results from start of current year to current time.
})