We have seen sum calculation using Aggregation.
In this post, we will see how to count the number of records from a field
- The
count
function counts the number of records from a field. - You can perform
count
query on numeric as well as non-numeric fields. - It can be performed with or without filters.
- The
distinct
filter gives the number of unique values for the selected field. - The
where
clause selects matching rows with specific field values.count
function then returns the count of the selected rows.
We will work with the same schema.
type AggObj {
intFld: Int
floatFld: Float
}
Let’s use the same 7 records from previous post.
mutation {
upsert(
values: {
AggObj: [
{ intFld: 1, floatFld: 1.1 }
{ intFld: 2, floatFld: 1.2 }
{ intFld: 3, floatFld: 1.3 }
{ intFld: 4, floatFld: 1.4 }
{ intFld: 4, floatFld: 1.4 }
{ intFld: 3, floatFld: 1.3 }
{ intFld: 1, floatFld: 1.1 }
]
}
) {
id
}
}
Sample Query
Let’s find out the count of all the floatFld
values.
{
aggregate {
aggObj {
floatFld {
count
}
}
}
}
#result
{
"data": {
"aggregate": {
"aggObj": {
"floatFld": {
"count": 7
}
}
}
}
}
Now, we will use the distinct
filter to find out the count of unique values. The below query considers repeated values from floatFld
as one value. So the count of records becomes 4 instead of 7.
{
aggregate {
aggObj {
floatFld {
count(distinct: true)
}
}
}
}
#result
{
"data": {
"aggregate": {
"aggObj": {
"floatFld": {
"count": 4
}
}
}
}
}
Let’s find out the count of the floatFld
values where intFld
values are 1.
{
aggregate {
aggObj (where: "intFld=1") {
floatFld {
count
}
}
}
}
#result
{
"data": {
"aggregate": {
"aggObj": {
"floatFld": {
"count": 2
}
}
}
}
}
Check the POSTMAN collection for the count
query in different programming languages! Click </>
and choose the programming language of your choice.
Don’t forget to insert your own Authorization key and Hypi Domain under Headers to test the results!