Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing range queries in Mongoose for Hour / Day / Month/ Year

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

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

like image 638
bob_cobb Avatar asked Jun 09 '13 10:06

bob_cobb


People also ask

How to set Date in Mongoose schema?

Here's how you declare a path of type Date with a Mongoose schema: const mongoose = require('mongoose'); const userSchema = new mongoose. Schema({ name: String, // `lastActiveAt` is a date lastActiveAt: Date }); const User = mongoose.

What does model find () return in Mongoose?

The Model. find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries.

How to pass Date in Mongoose?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

What is query in Mongoose?

The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.


1 Answers

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.
})
like image 149
Justin John Avatar answered Sep 30 '22 01:09

Justin John