【问题标题】:r mongolite - date queryr mongolite - 日期查询
【发布时间】:2016-03-30 23:19:41
【问题描述】:

问题

使用R 中的mongolite 包,如何查询给定日期的数据库?

示例数据

考虑一个包含两个条目的 test 集合

library(mongolite)

## create dummy data
df <- data.frame(id = c(1,2),
                 dte = as.POSIXct(c("2015-01-01","2015-01-02")))

> df
  id        dte
1  1 2015-01-01
2  2 2015-01-02

## insert into database
mong <- mongo(collection = "test", db = "test", url = "mongodb://localhost")
mong$insert(df)

Mongo shell 查询

要查找给定日期之后的条目,我会使用

db.test.find({"dte" : {"$gt" : new ISODate("2015-01-01")}})

如何使用mongoliteR 中重现此查询?

R 尝试

到目前为止我已经尝试过

qry <- paste0('{"dte" : {"$gt" : new ISODate("2015-01-01")}}')
mong$find(qry)
Error: Invalid JSON object: {"dte" : {"$gt" : new ISODate("2015-01-01")}}

qry <- paste0('{"dte" : {"$gt" : "2015-01-01"}}')
mong$find(qry)
 Imported 0 records. Simplifying into dataframe...
    data frame with 0 columns and 0 rows

qry <- paste0('{"dte" : {"gt" : ', as.POSIXct("2015-01-01"), '}}')
mong$find(qry)
Error: Invalid JSON object: {"dte" : {"gt" : 2015-01-01}}

qry <- paste0('{"dte" : {"gt" : new ISODate("', as.POSIXct("2015-01-01"), '")}}')
mong$find(qry)
Error: Invalid JSON object: {"dte" : {"gt" : new ISODate("2015-01-01")}}

【问题讨论】:

    标签: r mongolite


    【解决方案1】:

    @user2754799 有正确的方法,但我做了一些小改动,以便回答我的问题。如果他们想用这个解决方案编辑他们的答案,我会接受。

    d <- as.integer(as.POSIXct(strptime("2015-01-01","%Y-%m-%d"))) * 1000
    ## or more concisely
    ## d <- as.integer(as.POSIXct("2015-01-01")) * 1000
    data <- mong$find(paste0('{"dte":{"$gt": { "$date" : { "$numberLong" : "', d, '" } } } }'))
    

    【讨论】:

    • 因为 as.integer(as.POSIXct("2017-06-08", tz="GMT", origin = "1970-01-01"))*1000 返回 1.49688e+12,我建议粘贴“000”而不是乘以 1000。
    【解决方案2】:

    当我再次忘记如何在mongolite 中查询日期并且懒得去找文档时,这个问题一直出现在我的谷歌搜索结果的顶部:

    上面的Mongodb shell查询,

    db.test.find({"dte" : {"$gt" : new ISODate("2015-01-01")}})

    现在翻译成

    mong$find('{"dte":{"$gt":{"$date":"2015-01-01T00:00:00Z"}}}')

    您可以选择添加millis:

    mong$find('{"dte":{"$gt":{"$date":"2015-01-01T00:00:00.000Z"}}}')

    如果您使用错误的日期时间格式,您会收到一条有用的错误消息,指出正确的格式:use ISO8601 format yyyy-mm-ddThh:mm plus timezone, either "Z" or like "+0500"

    当然,这也记录在the mongolite manual

    【讨论】:

      【解决方案3】:

      从 github 尝试 mattjmorris 的回答

      library(GetoptLong)
      datemillis <- as.integer(as.POSIXct("2015-01-01")) * 1000
      data <- data_collection$find(qq('{"createdAt":{"$gt": { "$date" : { "$numberLong" : "@{datemillis}" } } } }'))
      

      参考:https://github.com/jeroenooms/mongolite/issues/5#issuecomment-160996514

      【讨论】:

      • qq的功能是什么?
      • 这是一个来自包GetoptLong的函数
      【解决方案4】:

      在将日期乘以 1000 转换日期之前,请执行以下操作:options(scipen=1000),因为缺少此解决方法会影响某些日期。

      这是解释here

      【讨论】:

        猜你喜欢
        • 2017-08-21
        • 1970-01-01
        • 2016-09-20
        • 2018-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多