Search code examples
raggregatepipelinemongolite

R/Mongolite: How to $unwind a dataframe?


I am using mongolite. I have an array in my dataset, which I would like to deconstruct using $unwind. I did the following:

pUsers <- pUsers$aggregate(pipeline = {"$unwind" : "$profile.hobbies"})

The result:

Error in "$unwind":"$profile.hobbies" : NA/NaN argument
In addition: Warning messages:
1: In inherits(x, "bson") : NAs introduced by coercion
2: In inherits(x, "bson") : NAs introduced by coercion

Seeing the error message, I tried to exclude data with NA value, with the following code:

pUsers <- pUsers$aggregate(pipeline = '[
        {"$match" : {"$profile.hobbies" : {"$exists" : true}}}, 
        {"$unwind" : "$profile.hobbies"}]')

Result:

Error: unknown top level operator: $profile.hobbies

Can someone explain the error I made? Moreover, how can I correctly unwind my dataframe? Thank you!


Solution

  • As commented, R's syntax does not conform to Mongo's query calls, specifically with curly braces and colons unlike other languages that can support these symbols in those positions.

    Therefore, be sure to wrap entire calls in quoted strings with all needed symbols such as square brackets. Specifically the following:

    pUsers <- pUsers$aggregate(pipeline = {"$unwind" : "$profile.hobbies"})
    

    Should be modified as

    pUsers <- pUsers$aggregate(pipeline = '[{"$unwind" : "$profile.hobbies"}]')