How to get field count? [solved]

Hi,

I am using autoform to gather answers to some multiple choice questions. None of the questions have answers required, i.e. some may choose to answer questions 1, 2, 5, some may choose to answer 2, 3, 4, etc.

I am trying to figure out how to get a count of the number of people who answered each question.

In theory, something like this would work.

Questions.find("age":{}).count()

In practice, not so much. Tried swapping {} for [] but still no luck. Any help towards a solution would be much appreciated.

UPDATE: OK, as I was writing this question, I figured it out and am posting my solution here in case someone else could use it.

   ageGroupTotal : function() {
        var ageEntries = Questions.find();
        var ageCount = 0;
        ageEntries.forEach(function(field){
            if(field.age){
                ageCount +=1;
            }
        });
        return ageCount;
    }

that’s highly inefficient. I’d go back to figuring out a cursor .count operation that works.

Try:

Questions.find({"age":{$exists:true}}).count();

http://docs.mongodb.org/manual/reference/operator/query/exists/

1 Like

@ahref Thanks! I’m glad I posted my question with my (inefficient) answer even when I got what I wanted. Your solution is way better and works beautifully!

No problem!

Be sure to checkout the mongo docs for other operators they are super cool!