R中使用mongolite的正则表达式

Kat*_*e K 4 r mongodb mongolite

试图与令人敬畏的mongolite图书馆进行正则表达式匹配,我仍然不确定我做错了什么,真的很疯狂,我在这里缺少什么.

library(mongolite)
m <- mongo(url = "mongodb://192.168.1.5:27017", db = "products", collection =    "sku")

m$count()
#gives 54524

a1 <- m$find('{"item"  : { "$regex" : "/.*A*./i" }}')
returns Imported 0 records. Simplifying into dataframe...

#but when you do
a1 <- m$find('{"item"  : "ABC"}')
#returns 8 records
a1 <- m$find('{"item"  : "AAC"}')
#returns 5 records
a1 <- m$find('{"item"  : "AAAC"}')
#returns 18 records
Run Code Online (Sandbox Code Playgroud)

等等.所以我不确定我在mongodb中调用正则表达式运算符的方式有什么问题.任何线索.?谢谢

Sym*_*xAU 7

在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" }  }
Run Code Online (Sandbox Code Playgroud)

而在mongo shell(我使用robomongo)你可以使用其中任何一个

db.test.find({ "val" : { "$regex" : /^a/ }  })
## or
db.test.find({ "val" : { "$regex" : "^a" }  })
Run Code Online (Sandbox Code Playgroud)

现在,如果你以后多一点的速度让你的数据导入R,以及您的结果可以被强制转换为data.table不丢失数据,可以使用一个包我已经写了扩展mongolite使用data.table::rbindlist转换的结果为data.table.获得速度是因为它假设您的数据处于"表格"结构并且避免了mongolite中的递归调用,这简化了JSON到data.frame.有关更多详细信息,请参阅我的github页面.

# 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
Run Code Online (Sandbox Code Playgroud)