Search code examples
rrmongodb

rmongodb: $exists gives empty result


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 ?


Solution

  • 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:

    ns <- "test.things"
    qs1 <- '{ "label": { "$exists": true } }'   # field exists
    qs2 <- '{ "none": { "$exists": true } }'    # field does not exist
    
    mongo.count( mongo, ns, qs1 )
    [1] 9
    
    mongo.count( mongo, ns, qs2 )
    [1] 0
    

    If you need to check whether two fields exist in one document, your JSON should look like this:

    qs3 <- '{ "name": { "$exists": true }, "schoolname": { "$exists": true } }'
    

    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 the rmongodb documentation for mongo.find()

    Arguments ...

    query ...

    Alternately, query may be a valid JSON character string which will be converted to a mongo.bson object by mongo.bson.from.JSON().