I am running mongodb query in R using rmongodb. I need to find whether certain field exists or not in the document. However, $exists doesnot produce any result. Here is sample code used for the query.
library(rmongodb)
> mongo <- mongo.create(host="localhost")
> dbns <- mongo.get.database.collections(mongo, db="namedisambiguation")
> buf <- mongo.bson.buffer.create()
> mongo.bson.buffer.start.object(buf, "name")
[1] TRUE
> mongo.bson.buffer.append(buf, "$exists", 1L)
[1] TRUE
> qrbson <- mongo.bson.from.buffer(buf)
> cur <- mongo.find(mongo, ns=dbns, query=qrbson)
> qrbson
name : 3
$exists : 16 1
> mongo.cursor.next(cur)
[1] FALSE
I have tried this query using TRUE, "True", "true", 1 instead of 1L, but all of these produces same result. I have checked this query in mongo console and the result is as needed. But in R, its producing empty. Am I doing wrong somewhere or anything ?
I can reproduce your problem and I guess it's a bug.
But what you could do is something along these lines here - code is tested with my database:
If you need to check whether two fields exist in one document, your
JSON
should look like this:This should get you to the desired result, although it's a bit different from your original approach in that is uses the
JSON
notation. From thermongodb
documentation formongo.find()