PyMongo Documentation

repository·main·Indexed 26 days ago

https://github.com/mongodb/mongo-python-driver

The official native Python driver for MongoDB, providing synchronous and asynchronous APIs for database interaction. The distribution includes the pymongo driver, the bson package for BSON format implementation, and the gridfs package for large file storage. It supports optional dependencies for GSSAPI, MONGODB-AWS, OCSP, Snappy, Zstandard, and Client-Side Field Level Encryption.

Tokens
27.3K
Snippets
25
Records
229
Agent score
87%

What's inside PyMongo

  1. Use json_util to work with BSON documents and Python's json module

    main
    The bson.json_util module provides tools to bridge the gap between BSON documents (which may contain types like ObjectId, datetime, or Binary) and Python's standard json module. It allows for the serialization and deserialization of BSON-specific types into a JSON-compatible format.
  2. Understand the PyMongo distribution packages

    main

    The PyMongo distribution is composed of three primary packages for interacting with MongoDB:

    1. bson: An implementation of the BSON (Binary JSON) format.
    2. pymongo: The full-featured driver used to interact with MongoDB databases.
    3. gridfs: A set of tools for working with the GridFS storage specification (used for storing large files).

    Depending on your needs, you may use one or all of these packages.

  3. Work with SON (Specially Ordered Notation) mappings

    main
    The bson.son module provides tools for working with SON, which is an ordered mapping. Unlike a standard Python dictionary (prior to Python 3.7), SON preserves the order of keys, which is critical for certain MongoDB operations where field order matters.
  4. Handle Collection.find empty projection behavior change

    main
    In PyMongo 4, an empty projection (e.g., {} or []) passed to find or find_one is passed to the server as-is. Previously, PyMongo substituted this with {"_id": 1}. Now, an empty projection will return the entire document. To maintain the old behavior of returning only the _id, explicitly specify the projection.
  5. Retrieve max BSON/Message/Write Batch sizes via hello command

    main

    The attributes max_bson_size, max_message_size, and max_write_batch_size have been removed from MongoClient. To get the authoritative values from the server, use the hello command.

    doc = client.admin.command('hello')
    max_bson_size = doc['maxBsonObjectSize']
    max_message_size = doc['maxMessageSizeBytes']
    max_write_batch_size = doc['maxWriteBatchSize']
  6. Migrate Collection.save to update_one or insert_one

    main

    The Collection.save method has been removed. For better performance, use insert_one to insert new documents and update_one to update existing ones. If you need a drop-in replacement that handles both (upsert), you can implement a custom function using replace_one with upsert=True.

    # Old
    doc = collection.find_one({"_id": "some id"})
    doc["some field"] = <some value>
    db.collection.save(doc)
    
    # New (Recommended)
    result = collection.update_one({"_id": "some id"}, {"$set": {"some field": <some value>}})
    
    # Manual save implementation if refactoring is not possible
    def save(doc):
        if '_id' in doc:
            collection.replace_one({'_id': doc['_id']}, doc, upsert=True)
            return doc['_id']
        else:
            res = collection.insert_one(doc)
            return res.inserted_id
  7. Migrate Collection.insert to insert_one or insert_many

    main

    The Collection.insert method has been removed. Replace it with insert_one for single documents or insert_many for lists of documents.

    # Old
    collection.insert({'doc': 1})
    collection.insert([{'doc': 2}, {'doc': 3}])
    
    # New
    collection.insert_one({'my': 'document'})
    collection.insert_many([{'doc': 2}, {'doc': 3}])