1

Earlier I used to use count() when I used to have a simple function of finding any product for example :

grocery = grocery.find({'Product':{'$regex':'.*?'+resultx,'$options':"i"}})

and then use the count() function on it to get the count like so which worked perfectly fine in giving me the count :

grocery.count() == 0:

But now I am using aggregate like so :

pipeline = [{'$match': {'Product':{'$regex':'.*?'+resultx,'$options':"i"}}},
            {'$lookup':{'from': 'othervendors','localField': 'Product','foreignField': 'Product','as': 'Matches'}}]
grocery = db.products.aggregate(pipeline)

and if I use count() on it :

grocery.count() == 0:

It throws me an error :

**AttributeError: 'CommandCursor' object has no attribute 'count'**

My question is, How do I use count() on the aggregate function

fear_matrix
  • 4,912
  • 10
  • 44
  • 65
  • `aggregate()` returns a [`CommandCursor`](https://api.mongodb.com/python/current/api/pymongo/command_cursor.html#pymongo.command_cursor.CommandCursor) and not a `Cursor` in the pymongo API. The difference is common to all language API's, and it does not have a `count()` method. Use a separate pipeline statement with [`$count`](https://docs.mongodb.com/manual/reference/operator/aggregation/count/) or it's `$sum: 1` equivalent. – Neil Lunn May 22 '18 at 06:24
  • If your pipeline allows it ( as yours presented here does ) because it does not do anything that cannot be done in a `find()` ( Thus only the `$match` since `$lookup` is just adding an array to the matched documents ) then run the `count()` from the same query condition on `.find()`. It's a lot faster than `$group` on a `null`|`""` value simply to count results. – Neil Lunn May 22 '18 at 06:28

0 Answers0