4

I have a date saved as a string like this tdate:"2016-11-26 2:23:11" in mongodb. I want to count all objects which have this date 2016-11-26. This is how I am trying to do using php but have no luck.

date_authenticated has this format "Y-m-d H:i:s" while I want to get all objects by day which should have this format "Y-m-d"

function count_auth($tdate) {
  $collection = 'mycollection';
  return $this->db->{$collection}->count(array('date_authenticated' => $tdate));
    }
sergiuz
  • 5,353
  • 1
  • 35
  • 51
Muya
  • 142
  • 1
  • 15

1 Answers1

1

If you have saved the date as a string you can find entries with MongoRegex like described in PHP mongo find field starts with. In your case it should be something like:

$startsWithRegex = '/^2016-11-26/'; 
$this->db->{$collection}->count(['date_authenticated' => array('$regex'=>new MongoRegex($startsWithRegex))]);

However I recommend you reading Find objects between two dates MongoDB as you can perform better queries if you handle dates properly.

Community
  • 1
  • 1
NiMeDia
  • 995
  • 1
  • 15
  • 27