简体   繁体   中英

rmongodb not returning distinct values for keys

I am using R to access a MongoDb table which contain records from Google Directions API. While I am able to access the _id values, I receive an error when trying to access a different key in the database data , - which is an array containing all of the information about routes. Any idea how to query an array using rmongodb ?

In the code below, first I check how many records are in the collection. Then using mongo.distinct() I query the database for all of the object ids, and then I run into a problem when I try to access the next index - data. Any idea why this is happening? I have included an image with information about both indices from MongoDB compass.

在此输入图像描述

> 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")

You should be able to query it exactly as you are trying.

In the absence of your data, here's a working example

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))

In a mongodb client (I'm using Robomongo) we can see data, and that image_url is an array

在此输入图像描述

So your query should work

## 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"

We can insert more data and run the same query

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM