r mongolite - date query

后端 未结 4 1439
执念已碎
执念已碎 2021-01-23 01:59

Question

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

Example Data

相关标签:
4条回答
  • 2021-01-23 02:11

    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

    0 讨论(0)
  • 2021-01-23 02:11

    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:

    0 讨论(0)
  • 2021-01-23 02:21

    @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, '" } } } }'))
    
    0 讨论(0)
  • 2021-01-23 02:36

    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

    0 讨论(0)
提交回复
热议问题