R中使用mongolite的正则表达式

时间:2016-05-17 22:49:45

标签: 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
等等。所以我不确定我在mongodb中调用正则表达式运算符的方式有什么问题。任何线索。?感谢

1 个答案:

答案 0 :(得分: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" }  }

然而在mongo shell中(我使用robomongo)你可以使用

db.test.find({ "val" : { "$regex" : /^a/ }  })
## or
db.test.find({ "val" : { "$regex" : "^a" }  })

现在,如果您将数据提升到R的速度更快,并且您的结果可以强制转换为data.table而不会丢失数据,那么您可以使用我的包写得延伸mongolite使用data.table::rbindlist将结果转换为data.table。获得速度是因为它假设您的数据处于“表格”结构并且避免了mongolite中的递归调用,这简化了JSON到data.frame。有关详细信息,请参阅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