Python and MongoDB: A Quick Reference to PyMongo

A constant frustration of mine is working with a library which is poorly documented and doesn't contain useful examples. As such, I have put together the following quick reference working with the PyMongo library for interactions between Python and the MongoDB storage facility. If there are any examples you would like to add, please feel free to drop them in the comments below. All comments require my approval before being posted so sorry if it takes a few days for them to appear- I receive too many bogus bot posts. The full PyMongo documentation is available at http://api.mongodb.org/python/ Installing the MongoDB Library $ easy_install pymongo or # sudo easy_install pymongo Importing the MongoDB Library import pymongo Connecting to MongoDB import pymongo mongo = pymongo.Connection('192.168.1.1') Selecting a Database import pymongo mongo = pymongo.Connection('192.168.1.1') # Returns Database Object mongo_db = mongo['my_database'] Selecting a Collection import pymongo mongo = pymongo.Connection('192.168.1.1') mongo_db = mongo['my_database'] # Returns Collection Object mongo_collection = mongo_db['my_collection'] Retrieve a Single Document import pymongo mongo = pymongo.Connection('192.168.1.1') mongo_db = mongo['my_database'] mongo_collection = mongo_db['my_collection'] # Returns a Dict mongo_document = mongo_collection.find_one({     'first_name': 'John',     'last_name': 'Doe' }) print mongo_document Retrieve Multiple Documents import pymongo mongo = pymongo.Connection('192.168.1.1') mongo_db = mongo['my_database'] mongo_collection = mongo_db['my_collection'] # Returns Cursor Object mongo_documents = mongo_collection.find({     'last_name': 'Doe' }) for this_document in mongo_documents:     print this_document Insert a New Document import pymongo mongo = pymongo.Connection('192.168.1.1') mongo_db = mongo['my_database'] mongo_collection = mongo_db['my_collection'] # Returns the '_id' key associated with the newly created document insert_id = mongo_collection.insert({     'first_name': 'John',     'last_name': 'Doe',     'dob': {         'month': 5,         'day': 14,         'year': 1984     } }) Delete an Existing Document import pymongo mongo = pymongo.Connection('192.168.1.1') mongo_db = mongo['my_database'] mongo_collection = mongo_db['my_collection'] # Deletes all records which match the first_name and last_name values specified. mongo_collection.remove({     'first_name': 'John',     'last_name': 'Doe' }); # Deletes the document matching the '_id' specified. mongo_collection.remove({     '_id': pymongo.objectid('4d1a0cecd518230437000000') }) Update an Existing Document import pymongo mongo = pymongo.Connection('192.168.1.1') mongo_db = mongo['my_database'] mongo_collection = mongo_db['my_collection'] mongo_collection.update(     { # The "where" clause         '_id': pymongo.objectid('4d1a0cecd518230437000000')     },     { # What you're updating         'balance': 0.00     } ) Update Multiple Documents import pymongo mongo = pymongo.Connection('192.168.1.1') mongo_db = mongo['my_database'] mongo_collection = mongo_db['my_collection'] mongo_collection.update(     {         'first_name': 'John'     },     {         'first_name': 'Greg'     },     multi=True )

4 Responses to “Python and MongoDB: A Quick Reference to PyMongo”

  1. Michael says:

    hah, interesting. I like Python

  2. ernest says:

    objectid is now (pymongo v1.9) part of bson. So when working with _id use bson.objectid insted of pymongo.objectid

  3. Jabba says:

    It is recommended to use safe=True for write operations (insert, update, remove, and findAndModify), otherwise MongoDB doesn’t check for errors.

  4. lisa says:

    Useful for testing / getting used to the API. Use with care in the 'real world'

    Remove all records from a collection:
    import pymongo
    mongo = pymongo.Connection('localhost', 27017)
    mongo_db = mongo['my_database']
    mongo_collection = mongo_db['my_collection']
    # Deletes all records which match the first_name and last_name values specified.
    mongo_collection.remove({})

Leave a Reply