You can use $where
which sends JavaScript to the server in order to query. But forget the prototype, since all logic must be self contained or otherwise loaded to the server. This means it must be evaluated in the function:
db.collection.find(function() {
return
( new Date(parseInt(this._id.toString().slice(0,8), 16)*1000)
> new Date("2015-01-01") ) &&
( new Date(parseInt(this._id.toString().slice(0,8), 16)*1000)
< new Date("2015-02-01") );
})
But it's not a great idea since $where
cannot use an "index" to filter out matches.
You are better of creating a "timestamp" field with an actual date object and using the $lt
and $gt
operators itself. That actual field can be indexed and the operators will use that to make a selection.
An alternate way is to work out what the ObjectId
values are outside of your query and then use the standard operators:
var start = ObjectId(
(new Date("2015-01-01").valueOf() / 1000).toString(16) + "0000000000000000")
),
end = ObjectId(
(new Date("2015-02-01").valueOf() / 1000).toString(16) + "0000000000000000")
);
db.collection.find({ "_id": { "$gt": start, "$lt": end } })
That creates ObjectId
values from the dates and allows you to use the primary key index that is always there.
Some drivers even support a "create from timestamp" method on their ObjectId
implementation.