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

2
  • aggregate() returns a 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 or it's $sum: 1 equivalent. Commented May 22, 2018 at 6: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. Commented May 22, 2018 at 6:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.