Reputation: 145
I'm using mongolite package to connect and retrieve data from MongoDB.How to pass value in mongolite find query
##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}',)
}
if I tried above code i'm getting getting below issues . please help me to resolve
Error: Invalid JSON object: {"field" : i}
Upvotes: 4
Views: 3244
Reputation: 1
The answers didn't work for me, but helped to start a new construction. So, thank you all.
I'm working with a huge quantity of items, thus I've stored the list in a vector and after I did the loop. In the loop I replaced the "paste0" for a "list" and I used "jsonlite::toJSON" to do the query, remove the [] is essential, so use "auto_unbox = TRUE".
Example:
items <- c("process","check","queue")
final_dataframe <- data.frame() #empty dataframe to store all results
for(i in items) {
values <- list(field = i) #vector in a correct format to query in mongolite using jsonlite
query_items <- mongo$find(jsonlite::toJSON(values, auto_unbox = TRUE), fields = '{}') #auto_unbox = TRUE to remove brackets and fields = '{}' to get "_id"
# filter relevant columns
query_items <- query_items %>%
select(`_id`, createdAt, deletedAt) %>%
mutate(items = i) #storing the items name/id
final_dataframe <- rbind(final_dataframe, query_items) #to store all results in a dataframe
}
Upvotes: 0
Reputation: 26248
Given your i
is a variable, you need to create the string using something like paste0
:
values <- mongo$find(paste0('{"field" : ', i, '}') )
but rather than a loop you could also use
values <- mongo$find('{"field" : { "$in" : [ "process", "check", "queue" ] } }')
Upvotes: 8