zoukankan      html  css  js  c++  java
  • mongodb 操作 Date字段类型 mongodb shell api

    一,环境

      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类库中的 MongoDBBSONUTCDateTime这种转化才可以

         $start= new MongoDBBSONUTCDateTime(strtotime("2020-03-11 00:40:34")*1000);
                    $end = new MongoDBBSONUTCDateTime(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类型的字段。

      

    PHP中常见的问题点,知识点,及盲点。
  • 相关阅读:
    Math类操作数据
    java之静态方法与非静态方法
    使用Date和SimpleDateFormat类表示时间
    Java 中基本类型和字符串之间的转换
    Python基础
    生成对抗网络
    机器翻译
    语义角色标注
    个性化推荐
    词向量
  • 原文地址:https://www.cnblogs.com/sblack/p/12492327.html
Copyright © 2011-2022 走看看