Mongodb和Codeigniter记录在两个日期之间



我正在努力使用CodeIgniter和MongoDB.Fetching记录获取两个日期之间的记录,但没有更正。

我的查询:

$startDate=date('d-m-Y',$startDate);
$endDate=date('d-m-Y',$endDate);
$this->mongo_db->select("*");
if ($startDate != '') {
$this->mongo_db->where_gte('created_date', $startDate);
}
if ($endDate != '') {
$this->mongo_db->where_lte('created_date', $endDate);
}
$this->mongo_db->where('id', $id);
$results = $this->mongo_db->get('tbl_test');

数据库中的记录,例如:

{ 
"_id" : ObjectId("xxxxxxxxx..."), 
"userId" : "4", 
"pId" : "365", 
"subject" : "hello", 
"description" : "testing", 
"status" : "0", 
"status_description" : "", 
"created_date" : "25-08-2018"
}

试图找到正确的解决方案..

理想的解决方案是将日期存储为日期类型而不是字符串,您的查询将正常工作。

{ 
"_id" : ObjectId("xxxxxxxxx..."), 
"userId" : "4", 
"pId" : "365", 
"subject" : "hello", 
"description" : "testing", 
"status" : "0", 
"status_description" : "", 
"created_date" : ISODate("2018-08-25T00:00:00Z") //YYYY-mm-ddTHH:MM:ssZ
}

如果存储日期不是一个选项,您可以使用下面的查询将日期字符串转换为日期,使用$dateFromString和 3.6 版本中可用的$expr

{$dateFromString: { dateString: "25-08-2018",format: "%d-%m-%Y"}}

Mongodb 查询:

db.colname.find({$expr:{$and:[{'$gte':[{'$dateFromString':{'dateString':'$created_date',format: '%d-%m-%Y'}},startDate]},  {'$lte':[{'$dateFromString':{'dateString':'$created_date',format: '%d-%m-%Y'}},endDate]}]}})

Date 在 strtotime(( 中。 我已将其更改为与存储在数据库中相同的格式

$startDate=date('Y-m-d',$startDate);
$endDate=date('Y-m-d',$endDate);
$this->mongo_db->select("*");
$searchCriteria =array('created_date' => array('$gte' => $startDate, '$lte' => $endDate),'id' => $id);
$this->mongo_db->where($searchCriteria);
$results = $this->mongo_db->get('tbl_test');

上面的代码经过测试,我已经完成了所有类型的测试。我只更改了日期的格式。

最新更新