Skip to content
wolfchimneyrock edited this page Jun 10, 2015 · 1 revision

Welcome to the mongolite wiki FAQ!


  • How do I perform CRUD (Create, Read, Update, Delete) operations using an id field of mongodb’s ObjectId type? I.e. if your data in the database looks like:


    {
            "_id" : ObjectId("5566470bfec60042d1f186ac"),
            "something" : "Gravy",
            "something_else" : "Train",
            "flavor" : {},
    }


    When reading a document into R from mongolite an ObjectId is converted automatically into a character vector, but when you attempt to query the database using that character vector it doesn’t automatically convert it back to an ObjectId. The solution is to use the “$oid” operator:


    > m = mongo(db="test",collection="test")
    > DocId = "5566470bfec60042d1f186ac"
    > query = sprintf('{"_id":{"$oid":"%s"}}',DocId)
    > m$find(query)
     Imported 1 records. Simplifying into dataframe...
      something something_else flavor                  
    1     Gravy          Train   NULL
    > m$update(query,'{"$set":{"flavor":{"primary":"Chicken","seconday":"Beef"}}}')
    [1] TRUE
    > m$find(query)
     Imported 1 records. Simplifying into dataframe...
      something somethingelse flavor.primary flavor.secondary                  
    1 Gravy Train Chicken Beef
    > m$remove(query)
    1 TRUE
    > m$find(query)
    Imported 0 records. Simplifying into dataframe…
    data frame with 0 columns and 0 rows
Clone this wiki locally