python模块整理19-pyMongo

一、pyMongo
1、安装
非标准库需要安装
#easy_install pyMongo
2、连接
使用pymongo.connecttion.Connection类与MongoDB服务器连接
from pymongo Connection
db=Connection('localhost',27017).apachelog #这里创建连接和使用库写在一起来了
>>> connection=pymongo.Connection('localhost',27017) #创建连接
>>> db = connection.test_database #切换数据库
获取collection
>>> collection = db.test_collection
db和collection都是延时创建的,在添加Document时才真正创建
3、插入数据
对于python来说,mongo的每一个文档都是一个字典
db.test.insert({'a':[1,2,3]})
db.test.find_One()
文档添加,_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)
批量插入
>>> 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)
多个文档组成列表插入
获取所有collection(相当于SQL的show tables)
>>> db.collection_names()
[u'posts', u'system.indexes']
4、查询
获取单个文档
>>> posts.find_one()
查询多个文档
>> for post in posts.find():
post
加条件的查询
>>> posts.find_one({"author": "Mike"})
高级查询
>>> posts.find({"date": {"$lt": d}}).sort("author")
统计数量
>>> posts.count()
3
5、更新数据
db.hourly.update({"hour":hour,"url":url},$inc:{"views":1},upsert=True)
5、创建索引
from pymongo import ASCENDING
db.hourly.create_index([("hour":ASCENDING),("url":ASCENDING)],uniqe=True)

posted on 2012-11-05 14:46  @Jin  阅读(441)  评论(0编辑  收藏  举报

导航