MongoDB/存储时间:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“如果使用string 或者时间戳 将会有以下优势 # 格式统一为熟悉的自己定义的类型,方便读写 # 数据的比较和数据的计算将会简…”
 
Kangkk​(留言 | 贡献)
 
(未显示同一用户的7个中间版本)
第1行: 第1行:
== Int ==
== ISODate ==
mongodb内置的时间类是ISODate,orm关系映射为java.util.Date类型,其保存的时间与我们会有8小时的区别(MongoDB自带的Date是UTC的时间,中国是东八区,所以差了8个小时。保存的时间比我们早了8个小时)。需要做时区转换。
== Timestamp ==
在实际编程过程中,发现保存timestamp容易,读取难。时间自1970年0点的秒数(或者毫秒数),类型是 64bit整数。
下面的代码可以将一个uint64_t(C++11的新类型)保存进MongoDB
<syntaxhighlight lang="C++">
mongo::BSONObjBuilder builder;
  builder.append("ip", cpu.ip);
  builder.append("host_name", cpu.host_name);
  builder.appendNumber("epoch", static_cast<long long>(cpu.epoch));
  builder.appendNumber("total_jiffies", static_cast<long long>(cpu.total_jiffies));
  builder.appendNumber("work_jiffies", static_cast<long long>(cpu.work_jiffies));
  session->get().insert("wind_tunnel.cpu", builder.obj());</syntaxhighlight>
读取数据的例子代码
<syntaxhighlight lang="C++">
uint64_t total1 = 0;
  uint64_t work1 = 0;
  if (!result.isEmpty()) {
    total1 = result.getField("total_jiffies").numberLong();
    work1 = result.getField("work_jiffies").numberLong();</syntaxhighlight>
== MongoDate ==
<syntaxhighlight lang="javascript">
//在数据库里存储一个时间
$collection->save(array("ts" => new MongoDate()));
//要查询的时间段
$start = new MongoDate(strtotime("2010-01-15 00:00:00"));
$end = new MongoDate(strtotime("2010-01-30 00:00:00"));
//查询时间段内的数据
$collection->find(array("ts" => array('$gt' => $start, '$lte' => $end)));</syntaxhighlight>
== String ==
如果使用string 或者时间戳 将会有以下优势
如果使用string 或者时间戳 将会有以下优势


第28行: 第62行:
beijing = utc + (3600000*offset);
beijing = utc + (3600000*offset);
data.DataTime = new Date(beijing);</syntaxhighlight>
data.DataTime = new Date(beijing);</syntaxhighlight>
== 时间格式的转换 ==
将数据库中的秒级时间戳,转换成Date类型,并且装换成任意时间格式
<syntaxhighlight lang="js">
db.t_merchant.aggregate(
{"$project":{
"create_time":{"$multiply":["$create_time", 1000]},
}},
{"$project":{
"create_time":{"$add":[ new Date(0), "$create_time" ]},
}},
{"$project":{
"create_time":{"$dateToString":{
date: "$create_time",
format: "%Y%m%d",
}},
}}
)</syntaxhighlight>
Timestamp类型转成ISODate
<syntaxhighlight lang="javascript">
var timestamp = Timestamp(1560506685, 958);//存储的时间戳格式
print( new Date( timestamp.t*1000+timestamp.i))//转换成日期类型</syntaxhighlight>
将时间戳(timestamp)转换为MongoDB中的ObjectId
javascript
<syntaxhighlight lang="javascript">
curr_dt=new Date()
curr_oid = Math.floor(curr_dt.getTime() / 1000).toString(16) + "0000000000000000";</syntaxhighlight>
shell
<syntaxhighlight lang="shell">
curr_dt='2019-02-25'
curr_ts='$(printf '%x' $(date -d "$curr_dt" +%s))'
curr_oid=$(printf '%-24s' ${curr_ts} |sed 's/ /0/g')</syntaxhighlight>
python
<syntaxhighlight lang="python">
from dateutil.parser import parse
from bson import ObjectId
import time
curr_dt = parse('2019-02-25')
curr_oid = ObjectId(hex(int(time.mktime(curr_dt.timetuple())))[2:] + '0'*16)</syntaxhighlight>
== 时间操作 ==
<syntaxhighlight lang="javascript">
db.getCollection("collections_name").aggregate( [
    {$match: { dtime: { $lte: '2019-12-20' , $gte: '2019-12-20' }, app_id:{$in: [1,2]}, platform:{$in: [2,3]} } },
    {
        $project: {
            dtime:1,
            date1: { $dateFromString: { dateString: '$dtime', } },  //String 转 date
            date2: { $add : [ { $dateFromString: { dateString: '$dtime' } } , 3*24*60*60*1000 ] }, //时间加3天,对应的减三天采用 $subtract
            date3: { $dateToString: { format: "%Y-%m-%d", date: { $dateFromString: { dateString: '$dtime' } } } }, //String转时间,并按指定格式显示
            date4: { $dateToString: { format: "%Y-%m-%d", date: { $add : [ { $dateFromString: { dateString: '$dtime' } } , 3*24*60*60*1000 ] } } }, //加上指定时间,并按指定格式显示
            date5: {$max: '$dtime'} //查看最大时间
        }
    }
] )</syntaxhighlight>