【问题标题】:How to insert document field value as ISODate with Ruby MongoDB driver?如何使用 Ruby MongoDB 驱动程序将文档字段值插入为 ISODate?
【发布时间】: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(&lt;ms_since_epoch&gt;.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


【解决方案1】:

我找不到任何关于此的文档,但如果您查看 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") }

ISODates 再次。

我在这里使用的是官方 Ruby 驱动程序的 2.2.5 版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 2013-04-03
    • 2022-01-08
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2012-04-05
    相关资源
    最近更新 更多