在 mongo shell 中,您可以使用不带引号的 / ... /。但是,在 mongolite 中,您需要引号,否则它是 invalid JSON
因此您需要使用... { "$regex" : ".*A*.", "$options" : "i"}...
考虑这个例子
library(mongolite)
m <- mongo(db = "test", collection = "test", url = "mongodb://localhost")
## create and insert some dummy data
set.seed(2016)
df <- data.frame(id = seq(1:100),
val = sample(letters, size = 100, replace = T))
m$insert(df)
## valid regex query in mongolite
m$find('{ "val" : { "$regex" : "^a", "$options" : "i" } }')
# Imported 5 records. Simplifying into dataframe...
# id val
# 1 26 a
# 2 53 a
# 3 61 a
# 4 76 a
# 5 100 a
## these queries don't work.
m$find('{ "val" : { "$regex" : "/^a/", "$options" : "i" } }')
# Imported 0 records. Simplifying into dataframe...
# data frame with 0 columns and 0 row
m$find('{ "val" : { "$regex" : /^a/, "$options" : "i" } }')
# Error: Invalid JSON object: { "val" : { "$regex" : /^a/, "$options" : "i" } }
而在 mongo shell(我使用 robomongo)中,您可以使用任何一种
db.test.find({ "val" : { "$regex" : /^a/ } })
## or
db.test.find({ "val" : { "$regex" : "^a" } })
现在,如果您希望更快地将数据输入R,并且您的结果可以强制转换为data.table 而不会丢失数据,您可以使用我编写的扩展@ 的包987654329@ 使用data.table::rbindlist 将结果转换为data.table。由于假设您的数据采用“表格”结构并避免了将 JSON 简化为 data.frame 的 mongolite 中的递归调用,因此速度会有所提高。有关详细信息,请参阅my github page。
# library(devtools)
# install_github("SymbolixAU/mongolitedt")
library(mongolitedt)
bind_mongolitedt(m)
m$finddt('{ "val" : { "$regex" : "^A", "$options" : "i" } }')
## returns a data.table
# Imported 5 records.
# id val
# 1: 26 a
# 2: 53 a
# 3: 61 a
# 4: 76 a
# 5: 100 a