一,環境
php 7.2 + thinkphp 5
mongodb 3.4
二,針對Date字段的操作
mongodb shell:
寫入:
db.students3.insert([ { "_id" : 1, "tests" : [ 95, 92, 90 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") }, { "_id" : 2, "tests" : [ 94, 88, 90 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") }, { "_id" : 3, "tests" : [ 70, 75, 82 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") } ]);
查詢:
db.students3.find({"lastUpdate":{$gte:new Date('2019-01-01')}})
三,PHP如何像操作時間戳那樣直接在DB中查詢Date字段類型呢?
1,試了好多種方法:原來一直以為可以直接用date類型的串就可以直接查詢,比較,然而沒鳥用!!!
例如 :
$s = date('Y-m-d H:i:s',strtotime('2020-03-11'));
$e = date('Y-m-d H:i:s',strtotime('2020-03-12'));
$where['time'] = ['between',[$s,$e]]
Db::connect('MONGO')->table('students3')->where($where)->select();
這樣是沒有結構,mongo識別不了這樣的時間字符串,不能像MYSQL那樣可以直接比較date字段類型的。
2,用php自的什么Datetime類型的也都沒用,要用mongodb類庫中的 MongoDB\BSON\UTCDateTime這種轉化才可以
$start= new \MongoDB\BSON\UTCDateTime(strtotime("2020-03-11 00:40:34")*1000);
$end = new \MongoDB\BSON\UTCDateTime(strtotime("2020-03-12 00:29:55")*1000);
$where['create_time'] = ['between',[$start,$end]];
$count = Db::connect('MONGO')->table('students3')->where($where)->count();
四,總結,之前沒用過mongodb,糾結嘗試了好久才可以正常操作Date類型的字段。