0

I'm trying to get a specific range of documents, based on when they were created. What I'm trying to do is something like:

  • /getclaims/2015-01
  • /getclaims/2015-02
  • ...

that way a user can browse through all records based on the selected month.

In my database I'm not storing a created_at date, but I know mongodb stores this in the objectid.

I found that I can get records like this:

db.claims.find({
        $where: function () { return Date.now() - this._id.getTimestamp() < (365 * 24 * 60 * 60 * 1000)  } 
 })

of course that doesn't filter based on a specific month, but only within a certain time limit.

What would be a possible way of limited a query based on a specific month, using the Timestamp from the objectid's?

I'm using mongoose, but it's probably a good idea to start in mongo shell itself.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Jorre
  • 17,273
  • 32
  • 100
  • 145
  • Ideally, you should add a `created` date field to your documents since you want to query on the created time of the documents. You should not use `$where` - it's very slow. – wdberkeley Feb 25 '15 at 15:55

1 Answers1

1

Based on the function borrowed from the answer to this question - https://stackoverflow.com/a/8753670/131809

function objectIdWithTimestamp(timestamp) {

    // Convert date object to hex seconds since Unix epoch
    var hexSeconds = Math.floor(timestamp/1000).toString(16);

    // Create an ObjectId with that hex timestamp
    return ObjectId(hexSeconds + "0000000000000000");
}

Create a start and an end date for the month you're looking for:

var start = objectIdWithTimestamp(new Date(2015, 01, 01));
var end = objectIdWithTimestamp(new Date(2015, 01, 31));

Then, run the query with $gte and $lt:

db.claims.find({_id: {$gte: start, $lt: end}});
Community
  • 1
  • 1
Alex
  • 37,502
  • 51
  • 204
  • 332