在猫鼬做范围查询小时/日/月/年



试着弄清楚怎么做。基本上我想按小时/日/月/年对我的提交进行排序。

每个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);
        }
    });
  });
有谁能帮我弄明白吗?在当前代码中,它只给我所有提交,而不考虑时间范围,显然我做得不对

我认为,您正在寻找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.
})

最新更新