我还不知道自己做错了什么,我真的很想知道我在这里错过了什么。
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等等。因此,我不知道在mongodb中调用regex操作符的方式有什么问题。有什么线索吗?谢谢
发布于 2016-05-18 01:55:38
在mongo中,您将使用没有引号的/ ... /。但是,在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 (我使用robomongo)中,可以使用
db.test.find({ "val" : { "$regex" : /^a/ } })
## or
db.test.find({ "val" : { "$regex" : "^a" } })现在,如果您需要更快地将数据导入R,并且您的结果可以在不丢失数据的情况下强制进入data.table,那么您可以使用我编写的一个包,该包扩展了使用data.table::rbindlist将结果转换为data.table的mongolite。速度是因为它假设您的数据是一个“表格”结构,并且避免了在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 ahttps://stackoverflow.com/questions/37287456
复制相似问题