Generally, as has been answered it is best to do this type of counting as close to the DB as possible. However sometimes you need to count based on more dynamic parameters, or you don't have access to the DB server/service. In these cases you can either use a Query of Queries, or if using CF11+ you can use an arrayFilter.
An example of the arrayFilter would look something like:
... snipped, see link below for full runnable example
// convert query to array of structs
peopleArray = deserializeJSON(serializeJSON(people,"struct"));
// filter the array as needed
notMatt = peopleArray.filter( function(a){
return a.firstname != 'Matt';
});
Then you could use the len()
or arrayLen()
function to get the count: i.e. notMatt.len()
The Query of Query option may be faster, haven't done any benchmarking, but that would look something like:
<cfquery dbtype="query" name="notMatt">
SELECT count(*) as total
WHERE firstname != 'Matt'
</cfquery>
Then you'd just use noMatt.total
. The below trycf gist shows both techniques (both in script form)
TryCF.com Examples