0

One can writeup the following script to run a find in pymongo:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydb"]
mycol = mydb["mycollection"]
mydoc = mycol.find()

If I want the count of results that went into that last line's find() result, is there a way to get it without running a separate mongo api call? Or, what is the simplest way to get the count given the code already there.

I do know that you can perform a count by invoking a server aggregate count. Is there a simpler way though that I am missing, or is that separate server operation request necessary?

paolov
  • 2,139
  • 1
  • 34
  • 43
  • The `find` method returns a _cursor_. The cursor object has many methods to work with , and there is method to count the documents in it (refer PyMongo documentation). There is also a method to count documents - without using the `find` method, `count_documents()`. – prasad_ Dec 09 '21 at 05:53
  • 1
    Does this answer your question? [In MongoDB's pymongo, how do I do a count()?](https://stackoverflow.com/questions/4415514/in-mongodbs-pymongo-how-do-i-do-a-count) – AlexisG Dec 09 '21 at 08:29
  • @prasad_, would you mind citing, and helping me please with what function it is specifically that would provide that count? Or what would the code look like. – paolov Dec 09 '21 at 11:15
  • @AlexisG - Thanks for the feedback. I had tried applying .count() on either mydoc or mycol per the code above and as suggested by the article you reference. It does not work/not exist. – paolov Dec 09 '21 at 11:18
  • 1
    PyMongo Tutorial on [Counting Documents](https://pymongo.readthedocs.io/en/stable/tutorial.html#counting). – prasad_ Dec 09 '21 at 11:36
  • @prasad_, all well and fine to point to documentation, but could you cite a specific solution that *directly* addresses the question as it is asked please. – paolov Dec 09 '21 at 12:14
  • You can try some searching the net using the string and lookup yourself: "Count with find using PyMongo" _or_ "PyMongo counting documents" are some search strings. Rest is your initiative and motivation. – prasad_ Dec 09 '21 at 12:27
  • @prasad_ I have searched and I know there is a way to do it, that involves invoking an aggregation count. My question is what is the simplest way, because invoking another server operation sure does not seem at all simple. And I wonder if there is something easy and simple that I am missing. – paolov Dec 09 '21 at 20:26

0 Answers0