1、安装

wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg
sudo sh setuptools-0.6c11-py2.7.egg
git clone git://github.com/mongodb/mongo-python-driver.git pymongo
cd pymongo/
sudo python setup.py install

2、引入驱动

import pymongo
from pymongo import Connection

3、建立连接

connection = Connection(‘localhost’, 27017)

4、获得数据库

db = connection.test_database

5、获得集合

collection = db.test_collection

6、建个文档

import datetime

post = {"author": "Mike",
        "text": "My first blog post!",
        "tags": ["mongodb", "python", "pymongo"],
        "date": datetime.datetime.utcnow()}

7、插入文档

posts = db.posts
posts.insert(post)

8、显示

db.collection_names()

9、使用find_one()获得一个单文档

posts.find_one()
posts.find_one({"author": "Mike"})

10、批量插入

new_posts = [{"author": "Mike",
              "text": "Another post!",
              "tags": ["bulk", "insert"],
              "date": datetime.datetime(2009, 11, 12, 11, 14)},
             {"author": "Eliot",
              "title": "MongoDB is fun",
              "text": "and pretty easy too!",
              "date": datetime.datetime(2009, 11, 10, 10, 45)}]

posts.insert(new_posts)

11、获得更多文档

for post in posts.find():
    print post
for post in posts.find({"author": "Mike"}):
    print post

12、统计

posts.count()
posts.find({"author": "Mike"}).count()

13、范围查询

d = datetime.datetime(2009, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
    print post

14、建立索引
想要获得快速的查询,可以在"date"和"author"上加一个复合索引 先用explain()方法获得没有索引的执行信息:

posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]
posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]

现在加上索引:

from pymongo import ASCENDING, DESCENDING

posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]
posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]

Comments