在你链接到它的答案中说
简单的答案是你不能这样做。
另请参阅相关的 mongodb 票证
但是,要以类似data.frame
结构的方式获得结果,请使用mongolite
,使用起来要容易得多
考虑这个使用mtcars数据的例子
data("mtcars")
library(mongolite)
mongo <- mongo(db = "test",
collection = "mtcars",
url = "mongodb://localhost")
## insert into database
mongo$insert(mtcars)
# Complete! Processed total of 32 rows.
# [1] TRUE
mongolite::find
会自动将查询结果简化为data.frame结构
df_results <- mongo$find()
# Imported 32 records. Simplifying into dataframe...
head(df_results)
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
或者,使用聚合框架
mongo$aggregate(pipeline = '[{ "$project" : { "mpg" : 1, "wt" : 1, "_id" : 0} },
{ "$limit" : 5 }]')
# Imported 5 records. Simplifying into dataframe...
# mpg wt
# 1 21.0 2.620
# 2 21.0 2.875
# 3 22.8 2.320
# 4 21.4 3.215
# 5 18.7 3.440
现在有点无耻的自我推销。我一直在研究返回 data.table 对象的 mongolite 扩展。这里的想法是提高返回对象的速度,但前提是返回的结果集可以使用rbindlist
.
该软件包是mongolitedt
,并且仍在开发中。
# devtools::install_github("SymbolixAU/mongolitedt")
library(mongolitedt)
bind_mongolitedt(mongo)
mongo$aggregatedt(pipeline = '[{ "$project" : { "mpg" : 1, "wt" : 1, "_id" : 0} },
{ "$limit" : 5 }]')
## now have a data.table object returned
# Imported 5 records.
# mpg wt
# 1: 21.0 2.620
# 2: 21.0 2.875
# 3: 22.8 2.320
# 4: 21.4 3.215
# 5: 18.7 3.440
## clean up
rm(mongo); gc()