【问题标题】:regex with mongolite in RR中带有蒙古石的正则表达式
【发布时间】:2016-09-14 05:20:33
【问题描述】:

尝试与很棒的 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 中调用正则表达式运算符的方式有什么问题。任何线索。?谢谢

【问题讨论】:

  • 您的正则表达式查询是否在 mongo shell 中工作?
  • 试试a1 &lt;- m$find('{ "item" : { "$regex" : ".*A*." , "$options" : "i"} }')

标签: r mongodb mongolite


【解决方案1】:

在 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

【讨论】:

  • 感谢您提供所有详细信息。也感谢 mongolitedt 库上的指针,看起来很有趣
  • @KateK - 没问题。请注意,mongolitedt 不在 CRAN 上,它仍在开发中,但应该足够稳定以供一般使用。
猜你喜欢
  • 2017-02-12
  • 2020-02-24
  • 2012-11-06
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
相关资源
最近更新 更多