Search code examples
rmongodbrmongodb

Mongo query that matches field to any element of array


I am trying to query a Mongo Db through R (rmongodb package). i have a simple requirement:

  • Return records where the field "email" matches any of the emails in the vector usr$email. I think I am close but just not able to find the right syntax to pull it through.

I saw this response to an earlier question (Mongo: If any array position matches single query) and am trying along the lines:

eids_l <- paste0("'", unique(usr$email), "'", collapse=", ")
eids_l1 <- sprintf("[ %s ]", eids_l)
q <- sprintf('{"email": {"$in": %s}}', eids_l1)
cursor <- mongo.find.all(mongo, namespace, buf)

I still get an error:

Error in mongo.bson.from.JSON(arg) : 
  Not a valid JSON content: {"email": {"$in": [ '[email protected]',

Solution

  • cursor <- mongo.find.all(mongo, "namespace", query='{ "email": { "$in": ["[email protected]", "[email protected]", "[email protected]" ] } }')

    Be careful with the use of apostrophes(') and quotation marks(").

    I always use the rmongodb Cheat sheet:

    https://cran.r-project.org/web/packages/rmongodb/vignettes/rmongodb_cheat_sheet.pdf