2016-11-29 84 views
4

我在mongodb中保存了一个像这样的字符串,如tdate:"2016-11-26 2:23:11"。我想要计算所有这个日期为2016-11-26的对象。 这就是我正在尝试使用php但没有运气。同时,我想通过day所有对象应该具有这种格式"Y-m-d"如何在mongodb和php中计算特定日期的对象

function count_auth($tdate) { 
    $collection = 'mycollection'; 
    return $this->db->{$collection}->count(array('date_authenticated' => $tdate)); 
    } 

回答

1

如果你已经保存日期为一个字符串,你可以找到MongoRegex条目等记载

date_authenticated具有这种格式"Y-m-d H:i:s"PHP mongo find field starts with。你的情况应该是这样的:

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

不过我建议你阅读Find objects between two dates MongoDB,如果你处理日期正确,你可以更好地执行查询。

+0

有用的答案我可以使用这个'$ startsWithRegex ='/^'.$ tdate。'/';'? – Muya

+0

是的,这应该是可能的 – P0rnflake