【发布时间】:2014-03-17 01:19:16
【问题描述】:
当我尝试使用 rmongodb 和 plyr 包将数据帧从 MongoDB 传输到 R 时,我遇到了一些奇怪的结果,其中包含大量集合集。我从有关该主题的各种 github 和论坛中获取此代码,并根据我的目的对其进行调整:
## load the both packages
library(rmongodb)
library(plyr)
## connect to MongoDB
mongo <- mongo.create(host="localhost")
# [1] TRUE
## get the list of the databases
mongo.get.databases(mongo)
# list of databases (with mydatabase)
## get the list of the collections of mydatabase
mongo.get.collections(mongo, db = "mydatabase")
# list of all the collections of my database
## Verify the size of mycollection
DBNS = "mycollection"
mongo.count(mongo, ns = DBNS)
# [1] 845923 documents inside "my collection"
## transform mycollection (in BSON MongoDB format) to a data frame (adapted for R)
export = data.frame(stringAsFactors = FALSE)
cursor = mongo.find(mongo, DBNS)
i = 1
while(mongo.cursor.next(cursor))
{
tmp = mongo.bson.to.list(mongo.cursor.value(cursor))
tmp.df = as.data.frame(t(unlist(tmp)), stringAsFactors = FALSE)
export = rbind.fill(export, tmp.df)
i = i + 1
}
## show the size of the database "export"
dim(export)
# [1] 20585 23
## check more information on the database "export"
str(export)
# 'data.frame': 20585 obs. of 23 variables
# etc…
传输做得不好:在 MongoDB 中找到的“mycollection”中的 845923 个文档与 R 中的 20585 个观察结果之间存在巨大差异。
我可能不同意上面的代码。如果我没有要附加的特定值,我不确定 i = 1 和 i = i + 1 是否对这个函数有用(可能来自带有 rmongodb 查询的代码)。我还发现“t(unlist(tmp))”很奇怪,t 是从哪里来的?
问题是我在 MongoDB 中的集合大小和 R 中的数据库大小之间遇到了一些很大的差异,其中包含大型集合集(优于数千个文档)。 我的 PC 具有良好的 RAM,并且 R 在此过程中似乎运行良好(没有冻结、没有崩溃、需要时间但由于从 BSON 到列表到数据帧的大量转换而正常)。
我已经成功地将一个包含 36100 个文档的 MongoDB 集合从 MongoDB 传输到 R 进行数据分析,没有任何问题。
所以我不确定问题出在哪里。
在此先感谢您对此主题的任何帮助。
【问题讨论】:
-
请提供一份 Mongo DB (JSON) 的示例文档。是否确定所有文档都具有该格式?
-
请提供 sessionInfo() 的输出和你的 mongodb 版本。我同样怀疑有一个文档,其中语法会导致导出问题并且连接中断。请检查错误:mongo.get.err(mongo) mongo.get.last.err(mongo, db) 并检查 ?mongo.get.err 以获取错误代码。
-
@Markus Sshmidberger : 'sessionInfo()' R 版本 3.0.2 (2013-09-25) 平台:x86_w64-mingw32/*64 (64- bit) […] [1] plyr_1.8 rmongodb_1.4.2 // 'mongo.get.err(mongo)' [1] 0 // 'mongo.get.lest.err(mongo, db="mydatabase")' NULL //
-
@Markus Sshmidberger :得到这个 'mongo.get.prev.err(mongo, db="my database") err :2 Invalid ns [mydatabase] code :16 应该很有趣16256 n:16 0 2 正常:1 1.000000
-
@vaettchen :当我执行 'try = mongo.find.one(mongo, ns = "my collection")' 时,我有一个典型的 BSON mongoDB 对象格式和 Twitter4j basicObj.put 作为回报 _id:7 52ff8e4394967e0f8351623 ID:18 434717890122489857 用户名:2 用户名日期:9 等等……
标签: r mongodb dataframe plyr rmongodb