如何使用Ruby MongoDB驱动程序将文档字段值插入为ISODate?

3

这可能很简单,但在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如此奇怪?为什么?

你尝试过插入一个日期对象吗? - mu is too short
@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 - 4Z4T4R
t本身怎么样?不尝试首先将其转换为DateTime - mu is too short
@muistooshort - 我已经更新了问题,并附上了我所有的尝试。 - 4Z4T4R
1个回答

3

我没有找到任何关于这个问题的文档,但如果你查看官方示例,你会发现如下内容:

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") }

我们需要的是ISO日期

然后,如果我们假装自己在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 版本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接