Search code examples
rethinkdbrethinkdb-pythonreqlrethinkdb-rubyrethinkdb-javascript

RethinkDB REQL Query to find number occurrences of distinct values in an array


I have a table like this in rethinkDB.

[{
    "Id": [
        12,
        13
    ],
    "group": "79",
    "go_Id": []
}, {
    "Id": [
        12,
        12,
        12,
        14
        14
    ],
    "group": "91",
    "go_Id": [
        16,
        16,
        16,
        19,
        19,
        20
    ]
}, {
    "Id": [
        12,
        12,
        13,
        13,
        11
    ],
    "group": "second",
    "go_Id": [
        16,
        17,
        17,
        16,
        17,
        17
    ]
}]

I want the Id and go_Id to have the count of the individual ids and the number of occurrences of them. So for example the desired output is

   [{
       "Id": [
           12: 1
           13: 1
       ],
       "group": "79",
       "go_Id": []
   }, {
       "Id": [
           12: 3
           14: 2
       ],
       "group": "91",
       "go_Id": [
           16: 3,
           19: 2,
           20: 1
       ]
   }, {
       "Id": [
           12: 2,
           13: 2,
           11: 1
       ],
       "group": "second",
       "go_Id": [
           16: 2,
           17: 4,
       ]
   }]

How should I go about it?

I tried to group based on id and then count but does not seem to work. Something like r.table('dev').group(r.row('Id"))


Solution

  • Something like this should work:

    r.table('dev').merge(function(row) {
      return {Id: row('Id').group(function(x) { return x; }).count().ungroup()};
    })