【发布时间】:2016-05-07 04:32:15
【问题描述】:
这可能真的很简单,但目前在 Ruby 领域中显而易见的是难以捉摸。
如何使用 Ruby MongoDB 驱动程序将文档字段值插入为 ISODate 而不是字符串?当我在 MongoDB shell 中查询一个集合时,我希望时间戳是一个 ISODate 对象:
{
"_id": ObjectId("570348904b3833000addcd67"),
"timestamp": ISODate("2016-04-04T21:23:52.058Z")
}
并且不是:
{
"_id": ObjectId("570348904b3833000addcd67"),
"timestamp": "2016-04-04T21:23:52.058Z" // or ms since epoch
}
请不要建议我从 epoch 开始使用 ms|s。这不是一个解决方案。
我试过了……
logs = []
t = Time.at(1448064510963.fdiv(1000))
mongo_hash['timestamp'] = t # --> String
mongo_hash[:timestamp] = t # --> String
mongo_hash['timestamp'] = t.to_datetime # --> Weird Date String
mongo_hash['timestamp'] = t.to_date # --> String without time
logs << mongo_hash
我正在将mongo_hash 推入一个数组,该数组将传递给insert_many。
mongo_client[:logs].insert_many(logs)
...我在 MongoDB 3.0.x 中得到的是一个使用 Ruby Mongo 驱动程序 v2.2.4 的时间戳字符串...
{
"_id": ObjectId("573107ac4f5bd9ac14920bb0"),
"timestamp": "2015-11-20T11:59:43.127-08:00"
}
JS/Python 中的小菜一碟……为什么这么奇怪,Ruby?为什么?
【问题讨论】:
-
您是否尝试过插入日期对象?
-
@muistooshort - 是的,确实如此。尝试首先创建
t = Time.at(<ms_since_epoch>.fdiv(1000)),然后在一个JSON对象中调用t.to_datetime(),该对象被推送到一个发送到mongo_client[:collection].insert_many()的数组中。仍然得到一个字符串值或TypeError - no implicit conversion of DateTime into String -
t本身呢?无需先尝试将其转换为DateTime。 -
@muistooshort - 我用我所有的尝试更新了这个问题。
标签: ruby-on-rails ruby mongodb