Skip to main content

A lightweight wrapper around pymongo to access MongoDB documents and subdocuments through custom user-defined classes.

Documents are returned as UserDict subclasses:

  • convenient pass-through to find() and find_one()

  • convenient load_by_id() to locate documents by ObjectId

  • smart save() function to insert, upsert or replace documents as appropriate

  • automatically record document creation and update times

  • track separate object schema versions

  • support polymorphic user objects loaded from the same collection

Subdocuments are accessed through dictionary proxy objects:

  • returned as their own classes independent of the parent MongoDB document class

  • data access is proxied back to the parent so no separate database access is performed

  • subdocuments have their own unique URL-safe ID useful for loading the data

  • subdocuments can be grouped in either dictionary or list containers

  • polymorphic subdocuments are supported within the same container

  • using subdocuments avoids “JOIN-like” additional database queries across collections

Example

Imagine an event ticketing system with a single MongoDB collection containing documents like the following:

{
    'name' : 'Fabulous Event',
    'date' : '...',      # datetime
    'desc' : 'This will be a lot of fun'
    'ticketTypes' : {
        '1' : {
            'name' : 'VIP Ticket',
            'desc' : 'Front-row seating; comes with a free plushie',
            'cost' : 200,
            'quantity' : 10,
        },
        '2' : {
            'name' : 'General Seating',
            'desc' : 'Everyone is welcome!',
            'cost' : 100,
            'quantity' : 100,
        },
    },
    'tickets' : [
        {
            'holder' : 'Fred',
            'purchased' : '...'      # datetime
            'ticketType' : 2,
        },
        {
            'holder' : 'Susan',
            'purchased' : '...'      # datetime
            'ticketType' : 1,
        },
    ]
}

MongoUserDict

mongo_objects allows us to create our own class for viewing these event documents:

class Event( mongo_objects.MongoUserDict ):

    db = ...     # provide your MongoDB database object here
    collection_name = 'events'

    def isFuture( self ):
        return self['date'] >= datetime.utcnow()

Loop through all events:

for event in Event.find():
    ...

Create a new event:

myevent = Event( {
    'name' : '...',
    'date' : '...',
} )
myevent.save()

Record the unique ID (ObjectId) of an event:

eventId = myevent.id()

Locate an event by its ID:

myevent = Event.load_by_id( eventId )

Call a method on our custom object:

myevent.isFuture()

MongoDictProxy

mongo_objects allows us to create additional proxy classes for managing subdocuments. The proxy classes behave like dictionaries but redirect all access back to the parent MongoUserDict object. No additional database access is performed.:

class TicketTypes( mongo_objects.MongoDictProxy ):
    container_name = 'ticketTypes'

First load an Event document object:

event = Event.find_one()

Loop through the existing ticket type subdocuments within the parent Event:

for tt in TicketTypes.get_proxies( event ):
    ...

Obtain a specific proxy by key:

tt = TicketType.get_proxy( event, '1' )

Get the unique ID of a proxy item:

ticket_type_id = tt.id()

Loading a proxy object by ID is a classmethod of the parent document class; the proxy can only exist once the parent document is loaded:

tt = Event.load_proxy_by_id( ticket_type_id, TicketTypes )

Create a new ticket type. A unique per-document key will be assigned automatically:

TicketType.create( event, {
    'name' : 'Student Ticket',
    'desc' : 'For our student friends',
    'cost' : 50,
    'quantity' : 25,
} )

Credits

Development sponsored by Headwaters Entrepreneurs Pte Ltd.

Originally developed by Frontier Tech Team LLC for the Wasted Minutes ™️ language study tool.

License

mongo_objects is made available to the community under the “MIT License”.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mongo_objects-1.1.2.tar.gz (34.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mongo_objects-1.1.2-py3-none-any.whl (11.0 kB view details)

Uploaded Python 3

File details

Details for the file mongo_objects-1.1.2.tar.gz.

File metadata

  • Download URL: mongo_objects-1.1.2.tar.gz
  • Upload date:
  • Size: 34.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.12.3

File hashes

Hashes for mongo_objects-1.1.2.tar.gz
Algorithm Hash digest
SHA256 908e92a69675fc172d5639d12eb3a6e4f3e69e8ec1c10c4429839f408224f0f7
MD5 2eca96238913637525b887ce2c99c0a0
BLAKE2b-256 17e6e5d4a63661a1cfff56e7df2acf7912fb55ef0ce856ae6ea0f6d00e23177f

See more details on using hashes here.

File details

Details for the file mongo_objects-1.1.2-py3-none-any.whl.

File metadata

  • Download URL: mongo_objects-1.1.2-py3-none-any.whl
  • Upload date:
  • Size: 11.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.12.3

File hashes

Hashes for mongo_objects-1.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d76981cc347cc610b024031efed8f7df70c2e2bdd5a81d4a20e1e32c7692d807
MD5 755ba0c2d76f8986ddc4ba0209638211
BLAKE2b-256 582dc45455c6272307d58d207c16456550cda81f6e78dd7b3234fd455c4d6417

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page