R-如何在m​​ongolite Query中传递值

时间:2017-11-02 07:01:58

标签: json r mongolite

我正在使用mongolite包来连接和检索来自MongoDB的数据。如何在mongolite查找查询中传递值

##connecting mongodb

library(mongolite)

mongo<-mongolite::mongo(collection = "Sample", db = "Test", url = 
                          "mongodb://User:123@Wyyuyu:13333/ty2_U",verbose = TRUE)

## getting all data from collection data from collection below query is working fine.

values <- mongo$find()

## But I want to filter specific value by passing value.

 for(i in c("process","check","queue"))
{    

   values <- mongo$find('{"field" : i}',)
}

如果我尝试上面的代码我会遇到问题。请帮我解决

Error: Invalid JSON object: {"field" : i}

1 个答案:

答案 0 :(得分:3)

鉴于您的i是变量,您需要使用paste0之类的内容创建字符串:

values <- mongo$find(paste0('{"field" : ', i, '}') )

但不是循环,你也可以使用

values <- mongo$find('{"field" : { "$in" : [ "process", "check", "queue" ] } }')