如何使用Java和R访问mongo查询结果的嵌套元素?

时间:2014-05-07 10:01:21

标签: java r mongodb

我正在使用Java和R从我的数据库中获取数据并实现预测。我在mongodb中的json就像:

{
 "Server" : [
    {
        "deviceName" : "NEWSCVMM",
        "availability" : 100,
        "osVersion" : "6.3.9600",
        "averageResponseTime" : 0.422,
        "useswapmemory" : "983040",
        "freeswapmemory" : "983040",
        "model" : "Virtual Machine",
        "numberOfCpu" : "1",
        "vendor" : "Microsoft Corporation",
        "vmList" : [ ],
        "macadd" : [ ],
        "cpuInfo" : "Intel(R) Xeon(R) CPU           X5670  @ 2.93GHz",
        "memory" : "6188596",
        "serialNo" : "00252-00000-00000-AA228",
        "cpuUtilization" : 0,
 }]

}

我想从那个json访问cpuUtilization。我试图使用(。)访问嵌套值,但得到结果为NULL。我也尝试在R shell上执行相同的操作,但结果为NULL。

这是我到目前为止所尝试的内容:

c.eval("query <- dbGetQuery(db,'   mycollection','{\"hostId\":\"0.0.0.0\",\"windowsServer.cpuUtilization\":{\"$ne\":\"null\"},\"runtimeMillis\":{\"$ne\":\"null\"}}')");
 c.eval("date <- query$runtimeMillis");
 c.eval("host_id <- query$hostId");
 c.eval("cpu <- query$Server.cpuUtilization");

 c.eval("all_data<-data.frame(cpu,date)");
 c.eval("training<- all_data");
 c.eval("rf_fit<-randomForest(cpu~date,data=training,ntree=500)");
 c.eval("new <- data.frame(date="+my_predicted_date+ ")");
 c.eval("predictions<-predict(rf_fit,newdata=new)");
 REXP memory_predictions= c.eval("predictions");

如何访问R shell上的嵌套元素或使用java?

1 个答案:

答案 0 :(得分:0)

Dot符号应该在Java中工作,我已经使用了很长一段时间了。 仔细检查你的代码,某处可能会有轻微的错误。

您能在这里发布部分代码吗?然后我可以看一看并发表评论。

这是我通常做的事情 - 让我们说我的文件是这样的 -

{_id:0, start : {x:10, y:50}, end : {x:20, y:100}}
{_id:1, start : {x:20, y:50}, end : {x:30, y:100}}
{_id:2, start : {x:30, y:50}, end : {x:40, y:100}}

如果我想根据起始字段中的“x”值进行查询,我会写这样的内容:

MongoClient client = new MongoClient();
DB db = client.getDB("YourDBNAME");
DBCollection collection = db.getCollection("YOURCOLLECTIONAME");
QueryBuilder builder =  QueryBuilder().start("start.x").greaterThan("20");
DBCursor cur = collection.find(builder.get());

while(cursor.hasNext())
{
 System.out.println(cursor.next());
}

将此代码段与您的代码段进行比较并查看。你应该让它工作正常。 如果这有帮助,或者您需要更多帮助,请告诉我。