Search code examples
rmongodbmongodb-queryrmongodb

Convert mongo objectid to string using rmongodb


I'm trying to convert a mongo collection to an R data frame. I'm using rmongodb package to do the same. I'm facing a problem with fields with the datatype "ObjectId" (in the code below, the column "_id"), rmongodb does not seem to recognize them as valid fields and thus excluding them from the OP dataframe. Is there a way to bulk convert ObjectId fields to string or extract their values?

query <- list(
mongo.bson.from.JSON('
{
"$project" : {
"_id" :0,
"app_id" : "$_id",
"column_1" : "$mongo_column_1",
#########################

I've already tried the functions:

ObjectId.toString()

and

ObjectId.valueOf()

But I think I'm making some syntactical errors and can't seem to find the right syntax to work in this situation.

P.S. I'm parsing the entire collection and not individual records.


Solution

  • I had the same problem this morning. Try using the mongo.oid.to.string function.

    l = mongo.bson.to.list(mongo.cursor.value(cursor))
    
    k <- mongo.oid.to.string(l[["_id"]])
    k
    "5242aef73edb350519b2bf3f"