1

我正在从提供程序中提取 JSON 数据并使用 R 将其添加到 mongodb。我计划在未来使用 R 和 Shiny 来显示数据。尽管我将数据放入 JSON 对象并将其插入 MongoDB,但我目前遇到了一个问题。它添加了对象,但将数据放置在比我真正想要的位置低一级的位置。

以下是数据的输入方式:

prettify(jsonKill)
[
    {
        "id" : {
            "timestamp" : 1409785080,
            "machine" : 11966932,
            "pid" : 3144,
            "increment" : 11720074,
            "creationTime" : "2014-09-03T22:58:00Z"
        },
    ...
]

这是我将其添加到 mongodb 的代码:

library('jsonlite')
library('rmongodb')

m <- mongo.create()
ns <- 'database.collection'
killObject <- fromJSON('http://omitted.because.nda:8000/api/omit')
x <- nrow(killObject)
for(i in 1:x){
  jsonKill <- toJSON(killObject[i:i,])
  bson <- mongo.bson.from.JSON(jsonKill)
  mongo.insert(m, ns, bson)
  paste("Inserting Record: ", i)
}
cursor <- mongo.find(m, ns, bson)
while(mongo.cursor.next(cursor)){
  value <- mongo.cursor.value(cursor)
  list <- mongo.bson.to.list(value)
  str(list)
}

结果如下:

{
    "_id" : ObjectId("54081299d5ec83d046d05766"),
    "1" : {
        "id" : {
            "timestamp" : 1409756219,
            "machine" : 2364985,
            "pid" : 9076,
            "increment" : 1079972,
            "creationTime" : "2014-09-03T14:56:59Z"
        },
    ...
}

我的目标是做一些具有这种效果db.collection.find({"id.pid" : $gt1})的索引mongo.index.create(m, ns, {"id.pid"}, mongo.index.unique),不一定是id键,而是此处未显示的一个或多个键。

4

2 回答 2

2

现在开箱即用。mongo.bson.from.list 现在可以将未命名列表转换为数组。

于 2014-10-01T08:36:43.590 回答
2

原因是 rmongodb 当前存在一个错误,该错误会妨碍数组的使用。


回复:

library(rmongodb)

m <- mongo.create()

json <- '{"array":[{"a":1},{"b":2}]}'
bson <- mongo.bson.from.JSON(json)

mongo.insert(m, "database.collection", bson)

MongoDB外壳:

> db.collection.find().pretty()
{
        "_id" : ObjectId("540825d68a271f234b6d62d2"),
        "array" : {
                "1" : {
                        "a" : 1
                },
                "2" : {
                        "b" : 2
                }
        }
}

为此,我开发了一个包(rmongodbHelper),它为该问题提供了解决方法:

回复:

library(devtools)
install_github("joyofdata/rmongodbHelper")
library(rmongodbHelper)

json <- '{"array":[{"a":1},{"b":2}]}'
bson <- rmongodbHelper::json_to_bson(json)

mongo.insert(m, "database.collection", bson)

MongodB外壳:

> db.collection.find().pretty()
{
        "_id" : ObjectId("540826738a271f234b6d62d4"),
        "array" : [
                {
                        "a" : 1
                },
                {
                        "b" : 2
                }
        ]
}

您可以在我的网站上找到有关此软件包以及将 MongoDB 与 R 结合使用的更多信息:

MongoDB - R 的状态


请记住,MongoDB 不能存储裸数组——只有对象——它们本身可能包含数组。

于 2014-09-04T08:47:32.957 回答