在 mongo shell 中,您将使用/ ... /
不带引号的。但是,mongolite
您需要引号,否则它是无效的 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
放入. 由于假设您的数据采用“表格”结构并避免了将 JSON 简化为 data.frame 的 mongolite 中的递归调用,因此速度会有所提高。有关详细信息,请参阅我的 github 页面。data.table
mongolite
data.table::rbindlist
data.table
# 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