Perl如何在mongodb中插入日期时间

时间:2018-08-13 16:37:35

标签: mongodb perl

我是MongoDB的新手,我将MySQL格式的日期存储在2018-08-13 09:56:19之类的数组中,我想将一个带有time_zone -0500的ISODate存储在MongoDB中,以便将日期插入为{{1 }}至"Date" : ISODate("2018-08-13T09:56:19.000-05:00")

感谢任何帮助...

1 个答案:

答案 0 :(得分:2)

您将需要使用使用MySQL格式的DateTime解析器,但是MongoDB会正确转换DateTime对象。但是,为了提高效率,查询时不会自动膨胀回DateTime对象,而是使用中间形式BSON::Time。有一种方法as_datetime用于获取DateTime对象。

请参见以下示例:

use Data::Dumper;
use DateTime::Format::MySQL;
use DateTime::Format::RFC3339;
use MongoDB;

# parse the date
my $dt = DateTime::Format::MySQL->parse_datetime( '2003-01-16 23:12:01' );
$dt->set_formatter("DateTime::Format::RFC3339");
say $dt;
# 2003-01-16T23:12:01+00:00

# set TZ
$dt->set_time_zone("America/New_York");
say $dt;
# 2003-01-16T23:12:01-05:00

# connect to the DB and get a MongoDB::Collection to work with
my $mc = MongoDB->connect("mongodb://localhost:27017");
my $coll = $mc->ns('test.foo');

# insert
$coll->insert_one({ date => $dt });

# query
my $doc = $coll->find_one({date => $dt});

# dump the doc -- note the date is now a BSON::Time and there's a
# MongoDB '_id' field added
say Dumper $doc;
# $VAR1 = {
#           '_id' => bless( {
#                             'oid' => '[vöZN@®G¿Ç'
#                           }, 'BSON::OID' ),
#           'date' => bless( {
#                              'value' => '1042776721000'
#                            }, 'BSON::Time' )
#         };

# get it back as a DateTime object and print it out
my $date = $doc->{date}->as_datetime;
$date->set_formatter("DateTime::Format::RFC3339");
say $date;
# 2003-01-17T04:12:01Z
$date->set_time_zone("America/New_York");
say $date;
# 2003-01-16T23:12:01-05:00