Reputation: 2688
I'm storing birth dates in mongodb using javascript
getTime() function. Now I want to query my db for all the people that are between 20 and 30 years. How can I do this on the server?
{ birth_date : { $gt : 20years, $lt : 30years } }
in db the date
looks like - 716763600000
Upvotes: 0
Views: 5574
Reputation: 691
Instead of using getTime(), it's probably better to work with Date objects directly. This way your data will be sent across the wire and stored tagged as the BSON datetime type rather than an integer type. You can insert and retrieve the current date like this:
> db.foo.insert({time: new Date});
> db.foo.findOne();
{
"_id" : ObjectId("523b182d42214dac3729419f"),
"time" : ISODate("2013-09-19T15:28:45.175Z")
}
And here is how you could query for everyone who is between 20 and 30 years old:
var t1 = new Date();
var t2 = new Date();
t1.setYear(t1.getYear() - 30);
t2.setYear(t2.getYear() - 20);
db.people.find({
birth_date : {$gt: t1, $lt: t2}
});
Upvotes: 2
Reputation: 10085
You have stored you birth dates as milliseconds since 1970/01/01. Then you have to query with a difference from then:
db.people.find({
birth_date: {
$gt: new Date().getTime() - new Date(2000, 0, 1).getTime(),
$lt: new Date().getTime() - new Date(1990, 0, 1).getTime()
}
})
In the $gt
command you query all, with a birthday greater than now before 30 years
In the $lt
command you query all, with a birthday lower than now before 20 years
Upvotes: 1