r mongolite - date query

≯℡__Kan透↙ 提交于 2019-12-20 05:17:10

问题


Question

Using the mongolite package in R, how do you query a database for a given date?

Example Data

Consider a test collection with two entries

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 query

To find the entries after a given date I would use

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

How can I reproduce this query in R using mongolite?

R attempts

So far I have tried

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

回答1:


@user2754799 has the correct method, but I've made a couple of small changes so that it answers my question. If they want to edit their answer with this solution I'll accept it.

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



回答2:


try mattjmorris's answer from github

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

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




回答3:


Prior converting your date by multiplying it with 1000, do this: options(scipen=1000), as the lack of this workaround will affect certain dates.

This is explained here:



来源:https://stackoverflow.com/questions/34454034/r-mongolite-date-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!