Prakash Thapa
Prakash Thapa

Reputation: 1285

How to create readable result of group function in RethinkDB without group and reduction field?

I have a query that uses group() function:

...group('a','b','c','na').count()

the now the result is returns like in the form of group and reduction like this:

enter image description here

How can I get result without group and reduce in the form of

{
"na": 1285
"c" : 487
"b" : 746
"a" : 32
}

Upvotes: 2

Views: 241

Answers (1)

Jorge Silva
Jorge Silva

Reputation: 4604

I'm not sure, but I think you're misunderstanding what group does.

The group command takes a property and groups documents by that property. So, for example, if you wanted to group documents by the a property, that would look something like this:

{
  a: 1
}, {
  a: 1
}, {
  a: 1
}, {
  a: 2
}

Then you would run the following query:

r.table(...).group('a').count().ungroup()

Which would result in:

[
  {
    "group": 1 ,
    "reduction": 3
  },
  {
    "group": 2 ,
    "reduction": 1
  }
]

By passing multiple arguments to group you are telling it to make distinct groups for all those properties. So you you have the following documents:

  [ {
    a: 1, b: 1
  }, {
    a: 1, b: 1
  }, {
    a: 1, b: 2
  }, {
    a: 2, b: 1
  }]

And you group them by a and b:

r.table(...).group('a', 'b').count().ungroup()

You will get the following result:

[{
  "group": [ 1 , 1 ] ,
  "reduction": 2
},
{
  "group": [ 1 , 2 ] ,
  "reduction": 1
},
{
  "group": [ 2 , 1 ] ,
  "reduction": 1
}]

Your Answer

So, when you do .group('a','b','c','na').count(), you're grouping them by those 4 properties. If you want the following result:

{
"na": 1285
"c" : 487
"b" : 746
"a" : 32
}

Then your documents should look something like this:

[{
  property: 'a'
}, {
  property: 'c'
}, {
  property: 'na'
}, 
...
]

And then you would group them in the following way:

r.table(...).group('property').count().ungroup()

Upvotes: 1

Related Questions