2016-07-13 117 views
1

我正在使用R访问包含来自Google Directions API的记录的MongoDb表。虽然我能够访问_id值,但在尝试访问数据库data中的不同密钥时收到错误 - 这是一个包含有关路由的所有信息的数组。任何想法如何使用rmongodb来查询数组?rmongodb不返回密钥的不同值

在下面的代码中,首先检查集合中有多少条记录。然后使用mongo.distinct()我查询数据库中的所有对象ID,然后在尝试访问下一个索引 - 数据时遇到问题。任何想法为什么发生这种情况?我已经包含了一个图像,其中包含来自MongoDB指南针的两个索引的信息。

enter image description here

> if(mongo.is.connected(mongo) == TRUE) { 
+ help("mongo.count") 
+ mongo.count(mongo, coll) 
+ } 
[1] 106500 



> res <- mongo.distinct(mongo, coll, "_id") 
> head(res) 
$`0` 
{ $oid : "57583d1057aa3d0499a85aab" } 

$`1` 
{ $oid : "57583d1157aa3d0499a85aad" } 

$`2` 
{ $oid : "57583d1257aa3d0499a85aaf" } 

$`3` 
{ $oid : "57583d1357aa3d0499a85ab1" } 

$`4` 
{ $oid : "57583d1457aa3d0499a85ab3" } 

$`5` 
{ $oid : "57583d1557aa3d0499a85ab5" } 



> res <- mongo.distinct(mongo, coll, "data.legs") 
Warning message: 
In mongo.distinct(mongo, coll, "data.legs") 
+0

您正在使用哪个mongodb库? (我猜'rmongodb'?) – SymbolixAU

+0

'images.thumbnail.url'字段是否存在于数据库中?它有数据吗? – SymbolixAU

+0

您能否提供样本文件?另外,你使用的是什么特定版本的MongoDB? – Stennie

回答

0

你应该能够准确地查询它,你正在尝试。

在没有数据的,这里的工作示例

library(rmongodb) 

mongo <- mongo.create(db = "test") 

## create some data 
lst <- list(lat = -37.9, 
      lon = 144.5, 
      image_url = letters) 

## insert data 
mongo.insert(mongo, "test.array_test", mongo.bson.from.list(lst)) 

在MongoDB的客户端(我使用Robomongo),我们可以看到数据,那image_url是一个数组

enter image description here

所以,你的查询应该工作

## query data on the 'image_url' array 
mongo.distinct(mongo, "test.array_test", key = "image_url") 
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" 

w^e可以插入更多的数据并运行相同的查询

lst <- list(lat = -37.8, 
      lon = 144.4, 
      image_url = c("string1","string2")) 

mongo.insert(mongo, "test.array_test", mongo.bson.from.list(lst)) 

mongo.distinct(mongo, "test.array_test", key = "image_url") 
# [1] "a"  "b"  "c"  "d"  "e"  "f"  "g"  "h"  "i"  "j"  "k"  "l"  
# [13] "m"  "n"  "o"  "p"  "q"  "r"  "s"  "t"  "u"  "v"  "w"  "x"  
# [25] "y"  "z"  "string1" "string2"