1

バックグラウンド

GTFSデータをローカルの mongodb データベースに保存しています。

calendarテーブルは次のようになります

field      | type
service_id | varchar
monday     | int (0 or 1)
tuesday    | int (0 or 1)
...
sunday     | int (0 or 1)

仕事

のパッケージservice_idを使用して、平日 (月曜日から金曜日) = 1 のすべての を選択したいと思います。rmongodbr

SQL では、これは次のようになります。SELECT service_id FROM calendar WHERE monday = 1 OR tuesday = 1 OR ... OR friday = 1

詳細

Robomongo GUIを使用する場合、クエリは次のとおりです。

db.getCollection('calendar').find({"$or" : 
    [{'monday':1},
    {'tuesday':1},
    {'wednesday':1},
    {'thursday':1},
    {'friday':1}]
})

8つのドキュメントを返します(画像を参照)

ロボモンゴクエリ

したがって、同じ結果を返すr同じクエリを作成しようとしていorますが、うまくいきません。

library(rmongodb)
library(jsonlite)
## connect to db
mongo <- mongo.create()
mongo.is.connected(mongo)
db <- "temp"

## days for which I want a service:
serviceDays <- c("monday","tuesday","wednesday","thursday","friday")

試行 0:

## create list as the 'query' condition
ls <- list("$or" = 
         list("monday" = 1L, 
              "tuesday" = 1L, 
              "wednesday" = 1L, 
              "thursday" = 1L, 
              "friday" = 1L))

services <- mongo.find.all(mongo, "temp.calendar", query=ls)
## returns error:
Error in mongo.find(mongo, ns, query = query, sort = sort, fields = fields,  : 
  find failed with unknown error.

試行 1:

## paste the string together
js <- paste0('{"', serviceDays, '":[',1L,']}', collapse=",")
js <- paste0('{"$or" :[', js, ']}')
## this string has been validated at jsonlint.com

bs <- mongo.bson.from.JSON(js)
## run query
services <- mongo.find.all(mongo, "temp.calendar", query=bs)
## result
> services
list()    ## empty list

## manually writing the JSON string doesn't work either
# js <- '{"$or" : [{"monday":[1]},{"tuesday":[1]},{"wednesday":[1]},{"thursday":[1]},{"friday":[1]}]}'

試行 2:

## create the or condition using R code
l <- as.list(sapply(serviceDays, function(y) 1L))
bs <- mongo.bson.from.list(list("$or" = list(l)))
## run query
services <- mongo.find.all(mongo, "temp.calendar", query=bs)
## result
> length(services)
[1] 2    ## 2 documents returned

返された 2 つのドキュメントは、月曜、火曜、水曜、木曜、金曜のすべてが 1 であるservice_ids のドキュメントです。ANDOR

試行 3:

## deconstruct the JSON string (attempt 1)
js <- fromJSON(js, simplifyVector=FALSE)
bs <- mongo.bson.from.list(js)

## run query
services <- mongo.find.all(mongo, "temp.calendar", query=bs)
## result
> services
list()    ## empty list

RRobomongo GUI を使用したときに取得したのと同じ 8 つのドキュメントを取得できないというクエリの試行の何が問題になっていますか?

4

1 に答える 1