mongo $where returning everything
-
21-12-2019 - |
Question
I am trying to find the documents in the database between specifit date ranges.
var event = {
to : 1393454361,
from : 1393354361
};
I have event.from
and event.to
as unix time integers and am using this to try and only return events, that are between the two date ranges:
db.events.find({
"event": "test",
"message.tableid": 123,
$where: function () {
return (
(event.from - this._id.getTimestamp()) > (event.from - event.to)
)
}
}).sort(
{ "message.time": -1 }
).forEach(function(error, x) {
if (error || !x) {
console.log("error getting items");
console.log("Current HPH in this range:");
console.log(hph);
} else {
console.log(
"Calc: ",
(event.from - x._id.getTimestamp() > (event.from - event.to))
);
if (event.from - x._id.getTimestamp() > (event.from - event.to)) {
hph = hph + 1;
}
}
})
For some reason, if I use an if
to check whether the date is between the ranges, it works.
But when I move my statement to the $where
-clause, all
documents get returned.
I just a bunch of documents in the collection that look like so:
{
"_id" : ObjectId("530cd8d610d28ebc27951eb8"),
"event" : "test",
"message" : {
"tableid" : 123
}
}
{
"_id" : ObjectId("530cd8d610d28ebc27952fb8"),
"event" : "test",
"message" : {
"tableid" : 123
}
}
Any ideas>?
If I try and use this as the $where
to check for the last 24 hours it works fine:
$where: function () {
return Date.now() - this._id.getTimestamp() < (1 * 60 * 60 * 1000)
}
Solution
You are not providing valid JSON. The mongo shell is very forgiving, other things are not.
db.events.find({
"$where":
"function () {
return Date.now() - this._id.getTimestamp() < (1 * 60 * 60 * 1000)
}"
}, function(err, result) {
// test err and process result
});
Since it's not valid, the condition means nothing. Equivalent to {}
in the .find()
.
Also, Try and re-factor to not use $where. You just threw away your index usage and forced a full table scan.
And as mentioned in comments, your long routing logic that can be simplified.
OTHER TIPS
Instead of using an if statement or a where clause try using the $gte and $lt operators in the query. Read this article: http://cookbook.mongodb.org/patterns/date_range/