Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8691319
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T00:06:06+00:00 2026-06-13T00:06:06+00:00

Is it possible in pymongo to have the collection.find() method return a custom cursor

  • 0

Is it possible in pymongo to have the collection.find() method return a custom cursor class that inherits from the base, but redefines how iteration occurs?

I’d like to instantiate app specific models from the mongo data within the cursor right at iteration time. The documents have a type attr that will determine what kind of instance should be created. I was thinking the next method could look within this data and decide which type to create and return. Inheriting from the cursor is easy enough, but I can’t figure out where to hook this into the find() operation?

EDIT Alternatively…

What I’m doing currently is to use yield to spit out a generator that will classify the object after the fact when the fetch is performed.

@classmethod
def gather(cls,place_id):
    """
    Gather instances of all the shouts for one place
    """
    shouts = cls.collection.find({'place_id':place_id})
    for s in shouts:
        yield Shout.classify(s)

@classmethod
def classify(cls,shout):
    if shout.type == 1:
        return Type1(dict(shout))
    elif shout.type == 2:
        return Type2(dict(shout))
    elif shout.type == 3:
        return Type3(dict(shout))

The problem is that this doesn’t preserve the original approach to bracket key access that is encapsulated in the default pymongo Cursor.

If I were to create a wrapper class that will just accept a cursor instance and wrap its methods, which magic methods will I need to override to preserve the iteration behavior of the original cursor? I’m thinking something like this:

class StuffCursor():

    cursor = False

    def __init__(self,cursor):
        self.cursor = cursor

    def __getattr__(self,attr):
        #This passes off most key-based calls, like bracket-access, to the cursor
        return getattr(self.cursor,attr)

This is just what I could think of, but anything that would stack some additional processing on top of an iterator, and then return the modified iterator, would work.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T00:06:07+00:00Added an answer on June 13, 2026 at 12:06 am

    Hate to answer my own question, but this may prove to be of good use to anyone googling. Here’s what I ended up going with:

    class ShoutCursor():
        """
        Custom cursor class that will instantiate shout models
        at query time.
        """
    
        cursor = False
    
        def __init__(self,cursor):
            self.cursor = cursor
            self.cursor.sort('created',DESCENDING)
    
        def __iter__(self):
            for ent in self.cursor:
                yield Shout.classify(ent)
    
        def __len__(self):
            return self.cursor.count()
    
        def __getitem__(self,index):
            try:
                ents = itertools.islice(self.cursor,index,index+1)
                return [Shout.classify(ent) for ent in ents][0]
            except TypeError:
                return list(Shout.classify(ent) for ent in itertools.islice(self.cursor,index.start,index.stop,index.step))
    
        def sort(*args,**kwargs):
            self.cursor.sort(*args,**kwargs)
    
        def __getattr__(self,attr):
            return getattr(self.cursor,attr)
    

    The __iter__ and __getiem__ methods are where the modified, instantiated models are loaded up into generators are returned. The other methods preserve native cursor action. Passing a cursor into __init__ sets up the functionality, so special, per iteration logic can be performed as the objects are fetched from mongo.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Extracting dollar amounts from existing sql data? I have a column in
results = docDB.posts.find({active:True }).sort(pop_score, pymongo.DESCENDING) This is my sort right now. But the problem
Is it possible to iterate over a pymongo Cursor as a key-value pair like
Is it possible to iterate over an pymongo.cursor.Cursor object in a django-template?
Possible Duplicate: Find out the instance id from within an ec2 machine I am
Possible Duplicate: JavaScript: why does parseInt(1/0, 19) return 18? Why does parseInt(1/0, 19) evaluate
Possible Duplicate: Can’t create handler inside thread that has not called Looper.prepare() inside AsyncTask
Possible Duplicate: get current latitude and longitude from gps enabled device I use the
Possible Duplicate: Why should the implementation and the declaration of a template class be
Is it possible to change the ObjectId field name from '_id' to 'id', or

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.