Uploaded image for project: 'Python Driver'
  1. Python Driver
  2. PYTHON-1724

How to count the items of a Cursor ?

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 3.7, 4.0
    • Component/s: API
    • Labels:
      None

      Since  https://jira.mongodb.org/browse/PYTHON-1581, the count method of Cursor is deprecated and the recommended method to get the total count is to use collection.count_documents.

      From https://jira.mongodb.org/browse/PYTHON-1667:

      cursor = collection.find({"foo": "bar"})
      count = cursor.count()
      

      becomes

      count = collection.count_documents({"foo": "bar"})
      

      My problem is, given a cursor that was created with a filter, I can get the collection, but AFAIK, I can't get the filter as it is stored in the private __spec attribute.

      I'm building a pagination helper that wraps a cursor. I used to write

      class PymongoCursorPage(Page):
          """Pager that deals with PyMongo cursor objects."""
          @property
          def item_count(self):
              return self.cursor.count()
      

      Now, I'd need to write something like this:

      class PymongoCursorPage(Page):
          """Pager that deals with PyMongo cursor objects."""
          @property
          def item_count(self):
              return self.cursor.collection.count_documents(  <<  filters >> )  # Where do I get this?
      

      I suppose I could wrap all the calls to `find` in my framework to add the filter to the cursor as a new attribute I could then use in my pagination wrapper to pass to collection.count, but that really sucks.

      Am I missing something?

      Could the filter be made available as a property like the collection?

       

            Assignee:
            bernie@mongodb.com Bernie Hackett
            Reporter:
            lafrech Jérôme
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: