python 使用 mongodb
easy_install pymongo
# 安装(python2.7+)
import pymongo connection=pymongo.Connection('localhost',27017) # 创建连接 db = connection.test_database # 切换数据库 collection = db.test_collection # 获取collection # db和collection都是延时创建的,在添加Document时才真正创建
文档添加, _id自动创建
import datetime post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()} posts = db.posts posts.insert(post) ObjectId('...')
批量插入
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) [ObjectId('...'), ObjectId('...')]
获取数据
获取所有collection
db.collection_names() # 相当于SQL的show tables
获取单个文档
posts.find_one()
数据查询
查询多个文档 for post in posts.find(): post 加条件的查询 posts.find_one({"author": "Mike"}) 高级查询 posts.find({"date": {"$lt": "d"}}).sort("author")
统计数量
posts.count()
加索引
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"]