在猫鼬中进行小时/天/月/年的范围查询 [英] Doing range queries in Mongoose for Hour / Day / Month/ Year

查看:260
本文介绍了在猫鼬中进行小时/天/月/年的范围查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to figure out how to do this. Basically I want to sort by Hour / Day / Month / Year of my submissions.

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

Each submission has a created field which contains a Mongoose Date object in the form of "created" : ISODate("2013-03-11T01:49:09.421Z"). Do I need to compare against this in the find() conditions?

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

Here is my current query (I'm wrapping it in a count for pagination purposes FWIW so just ignore that part):

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

有人可以帮我解决这个问题吗?使用当前的代码,它只给我所有提交内容,而不管时间范围如何,因此我显然做得不好

Can someone help me figure this out? With that current code it just gives me all submissions regardless of a time range, so I'm obviously not doing something properly

推荐答案

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

I think, you are looking $lt(Less than) and $gt(Greater Than) operators in MongoDB. By using above operators the result can be queried according to time.

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

I am adding possible solution below.

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

这篇关于在猫鼬中进行小时/天/月/年的范围查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆