Search code examples
rmongodb

how to iterate in a query of mongodb in R using rmongodb


I have my data in mongodb in collection "bd" which is in database "mydb". Its amazon review data and i am concerned with field "product/productId" and data related to it

#loading rmongodb library
library(rmongodb)
mongo <- mongo.create()
if(mongo.is.connected(mongo) == TRUE) 
{
#selecting mydb database
db <- "mydb"
mongo.get.database.collections(mongo, db)
} 
#selecting bd collection in mydb
coll = "mydb.bd"
#putting all productId in the res variable
if(mongo.is.connected(mongo) == TRUE) 
{
#since there are duplicate values of "product/productId" field,i stored only unique values of it
res <- mongo.distinct(mongo, coll, "product/productId")
} 
#logic to get review blob for a particular productId and here is where i get error
if (mongo.is.connected(mongo) == TRUE)
{
for(i in 1:length(res))
{
#getting error here while iterating for each productId stored in res[i] 
doc <- mongo.find.all(mongo,coll,'{"product/productId": res[i]}')
}
}
#but i get error in here as==>
#Error in mongo.bson.from.JSON(arg) : 
#Not a valid JSON content: {"product/productId": res[i]}

Solution

  • The answer is in error message - your JSON is not valid.

    q <- paste('{"product/productId":', res[i], '}')
    mongo.find.all(mongo, coll, q)
    

    or

    mongo.find.all(mongo, coll, list("product/productId" = res[i]))