这可能很简单,但在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
}
请不要建议我使用自公元纪年以来的毫秒数。这里不是解决方案。
我已经尝试过...
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)
我在使用Ruby Mongo驱动程序v2.2.4时,在MongoDB 3.0.x中得到的是一个时间戳字符串...
{
"_id": ObjectId("573107ac4f5bd9ac14920bb0"),
"timestamp": "2015-11-20T11:59:43.127-08:00"
}
在JS/Python中很容易,但是为什么Ruby如此奇怪?为什么?
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
。 - 4Z4T4Rt
本身怎么样?不尝试首先将其转换为DateTime
。 - mu is too short