Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor - Mongo aggregate does not have $count stage [duplicate]

I am using meteorhacks:aggregate package to do Mongo aggregation in Meteor. I want to get the count at the last stage of the pipeline so I use this code:

Message.aggregate([
  {
    $match: {
      // ...
    }
  }, {
    $count: 'count'
  }
]);

It is pretty simple and should work, but I only get this error:

Exception while invoking method 'methodname' 
MongoError: Unrecognized pipeline stage name: '$count'
...

Please help, thanks.

Updated: this question is not duplicated as an editor suggested, my main intention is to find out why I can not use $count

like image 708
kkkkkkk Avatar asked Jan 16 '17 06:01

kkkkkkk


People also ask

Which is not aggregation in MongoDB?

In MongoDB, the $not aggregation pipeline operator evaluates a boolean and returns the opposite boolean value. In other words, when the boolean evaluates to true , the $not operator returns false . And when the boolean evaluates to false , the $not operator returns true .

Which are the aggregation expressions used in MongoDB?

For the aggregation in MongoDB, you should use aggregate() method.

What passes through a MongoDB aggregation pipeline?

An aggregation pipeline consists of one or more stages that process documents: Each stage performs an operation on the input documents. For example, a stage can filter documents, group documents, and calculate values. The documents that are output from a stage are passed to the next stage.


1 Answers

$count is available in mongodb version 3.4. For previous versions, you will need to use $group over a constant field.

Message.aggregate([
  {
    $match: {
      // ...
    }
  }, {
    $group: {
      _id : null, 
      count : {$sum : 1}
    }
  }
]);
like image 188
ares Avatar answered Oct 25 '22 04:10

ares