这可能真的很简单,但目前在 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
}
请不要建议我从纪元开始就使用 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?为什么?
最佳答案
我找不到关于此的任何文档,但如果您查看 official examples ,你会看到这个:
result = client[:restaurants].insert_one({
#...
grades: [
{
date: DateTime.strptime('2014-10-01', '%Y-%m-%d'),
grade: 'A',
score: 11
},
#...
]
#...
})
这表明您可以使用简单的 DateTime
实例将时间插入 MongoDB。那么如果我们尝试这样做会发生什么?嗯:
irb> mongo[:pancakes].insert_one(:kind => 'blueberry', :created_at => DateTime.now)
然后在 MongoDB 中:
> db.pancakes.find()
{ "_id" : ..., "kind" : "blueberry", "created_at" : ISODate("2016-05-15T17:44:12.096Z") }
我们想要的 ISODate
就在那里。
然后假设我们在 Rails 中:
irb> require 'active_support/all' # To get to_datetime
irb> mongo[:pancakes].insert_one(:kind => 'banana', :created_at => '2016-05-15T06:11:42.235Z'.to_datetime)
我们在 MongoDB 中得到这个:
> db.pancakes.find()
{ "_id" : ObjectId("5738b56cf638ccf407c71ef5"), "kind" : "blueberry", "created_at" : ISODate("2016-05-15T17:44:12.096Z") }
{ "_id" : ObjectId("5738b74ef638ccf4da4c2675"), "kind" : "banana", "created_at" : ISODate("2016-05-15T06:11:42.235Z") }
ISODate
再次出现。
我在这里使用的是官方 Ruby 驱动程序 2.2.5 版。
关于ruby-on-rails - 如何使用 Ruby MongoDB 驱动程序将文档字段值作为 ISODate 插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084515/