【问题标题】:how to build query string elagantly in R for mongolite?如何在R中优雅地为mongolite构建查询字符串?
【发布时间】:2017-02-13 06:48:12
【问题描述】:

我想写一个函数来查询mongodb数据库的参数。

get_price = function(codes, start_date, end_date){
        query_string = '[{"$match":{"filedA":{"$in": codes}, "start_date":start_date, "end_date":end_date}},
                         {"$project":{"_id":0 }}
                      ]'
}


con$aggregate(pipeline=query_string)

但是构建查询字符串比较麻烦。

提前致谢。

【问题讨论】:

  • 对我来说,使用 SQL 查询的最简单方法是将它们保存在单独的 .sql 文件中,您可以在文本编辑器中使用漂亮的语法着色等进行处理,然后读入 R . 或者您可以使用paste0() 将查询拆分为多行以保持查询更简洁。
  • 这现在可能无济于事,但我正在处理mongolite pipeline package,其唯一目的是简化如何编写聚合查询。它仅处于开发的早期阶段,但请随时添加/建议改进

标签: r string mongodb mongolite


【解决方案1】:

我正在使用这个:

{
  bool_vector <- c(TRUE,FALSE)
  date_vector <- as.Date(c("2020-05-31","2020-06-30","2020-07-31") )
  str_vector <- c("string1","string2")
}

{
  bool_function<-function(bool_vector) {
  bool_json  <- ifelse(length(tolower(as.character(bool_vector))) %in% 2,
                       '{ "$in" : [ true, false ] }',tolower(as.character(bool_vector) 
                                                             ) 
                       )
  # as the field is named bool, the search vector should be bool_vector
  bool_field <- gsub("(.*)_.*","\\1",quote(bool_vector) ) 
  bool_json2 <- paste0('"',bool_field,'":',bool_json)
  return(bool_json2)
}

date_function<- function(date_vector) {
  # as the field is named date, the search vector should be date_vector
  date_field <- gsub("(.*)_.*","\\1",quote(date_vector) ) 
  
  date_json <- paste0('"',date_field,'":{"$gt":{"$date":"'
                      ,min(date_vector),'T00:00:00Z"},"$lt":{"$date":"'
                      ,max(date_vector),'T23:59:59Z"}}'
  )
  return(date_json)
}

str_function<-function(str_vector) {
  # as the field is named str, the search vector should be str_vector
  str_field <- gsub("(.*)_.*","\\1",quote(str_vector) ) 
  str_json   <- paste0("\"",paste0(str_vector,collapse= "\",\""),"\"")
  str_json_2 <- paste0('"',str_field,'":{"$in" : [',str_json,'] }')
  return(str_json_2)
}
}

vec_list <- mget(ls(pattern = "vector"))

make_query <- function(vec_list) {
json_list<-list()
i=0
for(vec in vec_list){
  i = i+1
  if(class(vec)=="logical"){
    json_list[[i]] <-bool_function(vec)
  } else if (class(vec)=="character") {
    json_list[[i]] <- str_function(vec)
  } else if (class(vec)=="Date") {
    json_list[[i]] <- date_function(vec)    
  }
}
query <- paste0("{",paste0(unlist(json_list),collapse = ","),"}")
return(query)
}

make_query(vec_list)

"{\"bool\":{ \"$in\" : [ true, false ] },\"date\":{\"$gt\":{\"$date\":\"2020-05-31T00:00:00Z\"},\"$lt\":{\"$date\":\"2020-07-31T23:59:59Z\"}},\"str\":{\"$in\" : [\"string1\",\"string2\"] }}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    相关资源
    最近更新 更多