0

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?

Tycho
  • 131
  • 1
  • 5

1 Answers1

1

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.

wdberkeley
  • 11,531
  • 1
  • 28
  • 23
  • needs an upvote, makes sense you can't regex over a date object, so the next best thing you can do is use $gte $lt operators – devonj Jun 20 '16 at 17:59