Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r mongolite - date query

Tags:

r

mongolite

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")}}
like image 423
tospig Avatar asked Mar 31 '26 16:03

tospig


2 Answers

@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, '" } } } }'))
like image 132
tospig Avatar answered Apr 02 '26 14:04

tospig


as this question keeps showing up at the top of my google results when i forget AGAIN how to query dates in mongolite and am too lazy to go find the documentation:

the above Mongodb shell query,

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

now translates to

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

optionally, you can add millis:

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

if you use the wrong datetime format, you get a helpful error message pointing you to the correct format: use ISO8601 format yyyy-mm-ddThh:mm plus timezone, either "Z" or like "+0500"

of course, this is also documented in the mongolite manual

like image 36
Janna Maas Avatar answered Apr 02 '26 12:04

Janna Maas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!