Python and MongoDB: A Quick Reference to PyMongo

2013年5月23日 11:09

Installing the MongoDB Library

$ easy_install pymongo
or
# sudo easy_install pymongo

Importing the MongoDB Library

from pymongo import MongoClient

Connecting to MongoDB

client = MongoClient("192.168.1.1", 27017)

Selecting a Database

client = MongoClient("192.168.1.1", 27017)
db_instance = client["database_name"]

Selecting a Collection

client = MongoClient("192.168.1.1", 27017)
db_instance = client["database_name"]
collection = db_instance["collection_name"]

Retrieve a Single Document

# Returns a Dict
mongo_document = mongo_collection.find_one({
    'first_name': 'John',
    'last_name': 'Doe'
})
print mongo_document

Retrieve Multiple Documents

# Returns Cursor Object
mongo_documents = mongo_collection.find({
    'last_name': 'Doe'
})
for this_document in mongo_documents:
    print this_document

Insert a New Document

# 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

# 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

mongo_collection.update(
    { # The "where" clause
        '_id': pymongo.objectid('4d1a0cecd518230437000000')
    },
    { # What you're updating
        'balance': 0.00
    }
)

Update Multiple Documents

mongo_collection.update(
    {
        'first_name': 'John'
    },
    {
        'first_name': 'Greg'
    },
    multi=True
)