6

试图弄清楚如何做到这一点。基本上我想按我提交的时间/天/月/年进行排序。

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

这是我当前的查询(出于分页目的,我将其包装在计数中,因此请忽略该部分):

  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);
        }
    });
  });

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

4

1 回答 1

17

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

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

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.
})
于 2013-06-09T16:31:57.040 回答