Reputation: 131
I have a collection of users and i want to get all the users who registered in 2015.
With a normal date string it is possible tot query:
$query=[
'timestamp'=> [
'$regex' => "2015"
]
];
But when I try this on a MongDate timestamp it doens't work anymore.
Any ideas?
Upvotes: 0
Views: 1517
Reputation: 11671
A date stored in MongoDB is not a string, it's a date type. You cannot match regular expressions against it because it is not a string. Instead, just search with a date range (and index the date field, if you want it to be fast):
db.test.find({ "timestamp" : { "$gte" : ISODate("2015-01-01T00:00:00.000Z"), "$lt" : ISODate("2016-01-01T00:00:00.000Z") } })
I'm not familiar with PHP so I wrote the query in mongo shell syntax.
Upvotes: 1