Skip to main content

mongo_objects

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 pymongo 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”.

Metadata

Release files for mongo-objects 1.2.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mongo-objects 1.2.6
File Size Uploaded Provenance
mongo_objects-1.2.6.tar.gz 845.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for mongo-objects 1.2.6
File Interpreter ABI Platform
mongo_objects-1.2.6-py3-none-any.whl Python 3 none any Details

Total release size: 861.3 kB

Release files / mongo_objects-1.2.6.tar.gz

Download URL mongo_objects-1.2.6.tar.gz
Size 845.9 kB
Tags Source
SHA-256 checksum
How to use checksums
dbb5c7028995cb00845fcdaaa4a59df74ee1a1e243e26c7828af280d564662bc
BLAKE2b-256 checksum
How to use checksums
917df661ef242a65a4cf52a849834b26829f19a0e393110c5bac80c809e35bae
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.12.5

Release files / mongo_objects-1.2.6-py3-none-any.whl

Download URL mongo_objects-1.2.6-py3-none-any.whl
Size 15.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8cf8922452eef2608d1f34d7dcd25b3eec4ce118a58a014f0fcab69d7d47ff39
BLAKE2b-256 checksum
How to use checksums
70acd8292e1f5040c9761189a99bd68cf21c149847a7fcde775b2604a51ed5fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.12.5

Security for mongo-objects 1.2.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page