gpt4 book ai didi

在 R 中使用 mongolite 的正则表达式

转载 作者:可可西里 更新时间:2023-11-01 09:10:37 28 4
gpt4 key购买 nike

尝试与令人敬畏的 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 中,您可以使用不带引号的 /.../。但是,在 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

关于在 R 中使用 mongolite 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287456/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com