Search code examples
rmongodbrmongodb

Converting mongo console, or RMongo query to rmongodb


I am having troubles with RMongo, so I'm trying to convert my work over to rmongodb. From here, my query looks like this in the mongo console:

db.final.find({},{"ids.myid":1,"org.name":1,"_id":0}).skip(0).limit(5000)

And like this in RMongo:

dbGetQueryForKeys(db,'final', '{}','{"ids.myid":1,"org.name":1,"_id":0}',skip=0,limit=5000)

(The latter is not returning values, but the Mongo console one does work.)

My understanding from the documentation is that it should look something like this in rmongodb:

library(rmongodb)
mcon <- mongo.create(host="myurl:port",db="dbname")

fields = mongo.bson.buffer.create()
mongo.bson.buffer.append(fields, "ids.myid", 1L)
mongo.bson.buffer.append(fields, "org.name", 1L)
mongo.bson.buffer.append(fields, "_id", 0L)

cur <-  mongo.find(mcon,"final",fields=fields, limit=5000) # query takes the default null
df <- mongo.cursor.to.data.frame(cur)

However, I'm getting:

data frame with 0 columns and 0 rows

What's the correct translation of my original query into rmongodb?

I know my connection is valid, because:

mongo.get.databases(mcon)

works and displays the correct databases. However, it seems there may be a problem with how I am calling the collection, because

mongo.find.one(mcon,"final") 

is returning NULL. This despite db.final.findOne() working fine!


Solution

  • The namespace (ns) of your collection is wrong. The name of your db is missing. Try this:

    cur <-  mongo.find(mcon,"dbname.final",fields=fields, limit=5000)
    

    and

    mongo.find.one(mcon,"dbname.final")