服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - MongoDB - Mongodb 如何将时间戳转换为年月日日期

Mongodb 如何将时间戳转换为年月日日期

2022-11-28 15:37lMasterSparkl MongoDB

这篇文章主要介绍了Mongodb 如何将时间戳转换为年月日日期,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Mongodb将时间戳转换为年月日日期

使用dateToString 方法进行转换 并且通过format指定转换日期格式

?
1
2
3
4
5
6
7
8
        Integer userId=aaa;
        GroupOperation groupOperation = Aggregation.group("day").sum("money").as("todayIncome").count().as("todayPayCount");
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("userId").is(userId)),
                project("userId","money").andExpression("{$dateToString: {date: { $add: {'$createTime', [0]} }, format: '%Y%m%d'}}", new Date(28800000)).as("day"),
                groupOperation,
                sort(Sort.Direction.ASC, "_id")
        );

注意:

1.必须使用 $dateToString: {date: { $add: 通过求和进行date数据转换 如果去掉后面的会报解析错误

org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 16006 (Location16006): 'can't convert from BSON type long to Date' on server localhost:50000. The full response is {"ok": 0.0, "errmsg": "can't convert from BSON type long to Date", "code": 16006, "codeName": "Location16006"}; nested exception is com.mongodb.MongoCommandException: Command failed with error 16006 (Location16006): 'can't convert from BSON type long to Date' on server localhost:50000. The full response is {"ok": 0.0, "errmsg": "can't convert from BSON type long to Date", "code": 16006, "codeName": "Location16006"}

2.必须增加 new Date(28800000) 的时间 原因是增加了8个时区的偏移量

MongoDB中的日期查询的坑

在熟悉monggoDB的时候遇到了时间查询的问题代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
 
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
 
/**
 * mongo 数据库直连测试
 * @author fuhao
 *
 */
public class MongDBTest {
    public static void main(String[] args) throws Exception {
        List<ServerAddress> list = new ArrayList<ServerAddress>();
//      连接数据库   ip 端口
        list.add(new ServerAddress("10.39.XXX.XXX", 27010));
        MongoClient mongoClient = new MongoClient(list);
        //数据库名称
        DB psdoc = mongoClient.getDB("qa_db_center");
        //表明
        DBCollection collection=psdoc.getCollection("base_user_info");
        
        BasicDBObject queryObject = null;
        
        // 时间查询    数据库看到的时间不是真实时间  加8小时后才是正确的时间
        DBObject dbObject = new BasicDBObject();
        String startDate = "2018-03-29 15:59:06";
        String endDate = "2018-03-29 16:30:46";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dbObject.put("$gte", sdf.parse(startDate));
        dbObject.put("$lte",  sdf.parse(endDate));
        queryObject = new BasicDBObject();
        queryObject.put("create_time",dbObject);
        DBCursor find = collection.find(queryObject);
         
        while (find.hasNext()) {
             DBObject next = find.next();
             Object real_name = next.get("real_name");
             Object mobile = next.get("mobile");
             Object create_time = next.get("create_time");
             String str = sdf.format(create_time);
             System.out.println(real_name +"====="+mobile +"====="+str);
        }
         System.out.println("结束");
        
    }
}

请求页面 默认页 https://blog.csdn.net/qq_27292113/article/details/91876121 【标题】:MongoDB中的日期查询的坑_天马行空-的博客-CSDN博客_mongodb query 日期 【内容】:

在熟悉monggoDB的时候遇到了时间查询的问题代码如下:

上面的代码中查询时间 按mysql 的流程应该查询到 2018-03-29 15:59:06 到2018-03-29 16:30:46 这个区间的数据,但是mongoDB不同,因为mongo中的date类型以UTC(Coordinated Universal Time)存储,就等于GMT(格林尼治标准时)时间。而系统时间使用的是GMT+0800时间,两者正好相差8个小时。也就是用java 代码插入的时间类型的值都会被减8小时。这个坑挺大的不注意很容易出事。

展示一下对比数据便于理解:

Mongodb 如何将时间戳转换为年月日日期

上面的圈是查询的条件对应数据库中的数据是2018-03-29T08:30:36.310Z 如下图,但是在java中你写2018-03-29 08:30:36这个时间肯定查不到数据

Mongodb 如何将时间戳转换为年月日日期

对比得出数据库中看到的时间和实际时间差8小时,但是查询出来的结果时间还是会被转换回来(不以时间为条件查询的话基本没什么问题)。

记录一下mongoDB中查询区间时间的执行语句:

?
1
db.getCollection('base_user_info').find({"create_time":{"$gte":ISODate("2018-03-29 07:59:06"),"$lte":ISODate("2018-03-29 08:30:46")}});

base_user_info :表名  create_time:字段名

比较符号对应列表

  • $gt -------- greater than  >
  • $gte --------- gt equal  >=
  • $lt -------- less than  <
  • $lte --------- lt equal  <=
  • $ne ----------- not equal  !=
  • $eq  --------  equal  =

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/lMasterSparkl/article/details/109679841

延伸 · 阅读

精彩推荐
  • MongoDBMongoDB数据查询方法干货篇

    MongoDB数据查询方法干货篇

    查询操作在我们日常操作数据库的时候是必不可少的一部分,最近有些空闲时间,所有就将MongoDB数据查询的一些方法技巧总结了处理,这篇文章主要介绍了...

    Chenjiabing3782020-05-12
  • MongoDBLinux下MongoDB数据库实现自动备份详解

    Linux下MongoDB数据库实现自动备份详解

    这篇文章主要给大家介绍了在Linux系统下下MongoDB数据库实现自动备份的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需...

    逝水-无痕4292020-05-13
  • MongoDBmongodb权限设置之添加管理员、普通用户的方法

    mongodb权限设置之添加管理员、普通用户的方法

    这篇文章主要介绍了mongodb添加管理员、普通用户的方法,同时介绍了mongodb开启权限认证后PHP客户端的两种连接方法,需要的朋友可以参考下 ...

    MongoDB教程网10232020-04-25
  • MongoDBMongoDB中MapReduce的使用方法详解

    MongoDB中MapReduce的使用方法详解

    MapReduce应该算是MongoDB操作中比较复杂的了,下面这篇文章主要给大家介绍了关于MongoDB中MapReduce使用的相关资料,文中通过示例代码介绍的非常详细,需要...

    独孤求败2282020-05-16
  • MongoDBSpringBoot整合MongoDB的实现步骤

    SpringBoot整合MongoDB的实现步骤

    MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。本文介绍SpringBoot项目如何整合MongoDB...

    消灭知识盲区5632021-08-23
  • MongoDBNoSQL优缺点与mongoDB数据库简介

    NoSQL优缺点与mongoDB数据库简介

    这篇文章介绍了NoSQL的优缺点与MongoDB数据库,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...

    springsnow4062022-06-06
  • MongoDBMongoDB使用mongoexport和mongoimport命令,批量导出和导入JSON数据到同一张表的实例

    MongoDB使用mongoexport和mongoimport命令,批量导出和导入JSON数据到同一

    今天小编就为大家分享一篇关于MongoDB使用mongoexport和mongoimport命令,批量导出和导入JSON数据到同一张表的实例,小编觉得内容挺不错的,现在分享给大家,具...

    李学凯2772020-05-19
  • MongoDBMongoDB 用户管理

    MongoDB 用户管理

    这篇文章主要介绍了MongoDB 如何对用户管理,帮助大家更好的理解和使用MongoDB数据库,感兴趣的朋友可以了解下...

    mySoul3222020-09-12