Search code examples
rmongodbrmongodb

How to query a Document by ObjectId with rmongodb


Here is what you get in mongo shell :

db.col.find(ObjectId("5571849db1969e0a6eb32731")).pretty()
{   
"_id" : ObjectId("5571849db1969e0a6eb32731"),
    "name" : "Some name",
    "logo" : "Some logo",
    "users" : [
        ObjectId("5571830031c7fc341bc2e105"),
        ObjectId("5571830031c7fc341bc2e107")
    ],
    "admins" : [ ],
    "__v" : 0,
    "steps" : 5782
}

Here is what I get in rmongo :

myResult <- mongo.find(Connexion, "db.col", query='ObjectId("5571849db1969e0a6eb32731")')

#Error in mongo.bson.from.JSON(arg) : 
#  Not a valid JSON content: ObjectId("5571849db1969e0a6eb32731")

So, how to do it right ?

Just in case : I had a look at this already. But mongolite doesn't support authentication (which is therefore a no-go) and I don't understand what to do with the second answer. If I try

result <- mongo.find(Connexion, "db.col", query=mongo.oid.from.string("5571849db1969e0a6eb32731"))

I get

# Error in mongo.bson.from.argument(query) : Can't convert to bson: argument should be one of 'list', 'mongo.bson' or 'character'(valid JSON)

Solution

  • This should work:

    result <- mongo.find(Connexion, "db.col", query=list('_id' = mongo.oid.from.string("5571849db1969e0a6eb32731")))