中关村村草 发表于 2011-03-02 13:13

python调用MongoDB使用心得

转:stonelee


python调用MongoDB使用心得





下载相应平台的版本,解压即可。为方便使用,将bin路径添加到系统path环境变量里。其中mongod是服务器,mongo是客户shell
然后创建数据文件目录:在c盘下创建data文件夹,里面创建db文件夹。

基本使用:



下载对应语言的Driver
python

Python代码$ easy_install pymongo使用方法总结,摘自官方教程

make a connection

Python代码>>> import pymongo
>>> connection=pymongo.Connection('localhost',27017)get a database

Python代码>>> db = connection.test_databaseget a collection

Python代码>>> collection = db.test_collectiondb和collection都是延时创建的,在添加Document时才真正创建

Documents

Python代码>>> import datetime
>>> post = {"author": "Mike",
...         "text": "My first blog post!",
...         "tags": ["mongodb", "python", "pymongo"],
...         "date": datetime.datetime.utcnow()}insert Document into collection
_id自动创建

Python代码>>> posts = db.posts
>>> posts.insert(post)
ObjectId('...')批量插入

Python代码>>> 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)
list all collections

Python代码>>> db.collection_names()
Get Single Document

Python代码>>> posts.find_one()
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': }查询返回多个结果

Python代码>> for post in posts.find():
...   post
...
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': }
{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': }
{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'}加条件的查询

Python代码>>> posts.find_one({"author": "Mike"})高级查询

Python代码>>> posts.find({"date": {"$lt": d}}).sort("author")统计数量

Python代码>>> posts.count()
3加索引

Python代码>>> from pymongo import ASCENDING, DESCENDING
>>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
u'date_-1_author_1'查看sql语句的性能

Python代码>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]
u'BtreeCursor date_-1_author_1'
>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]
2附自己总结的一点小心得,仅供参考
not only sql

缺点
不是全盘取代传统数据库
不支持复杂事务
文档中的整个树,不易搜索,4MB限制?

特点:
文档型数据库,表结构可以内嵌
没有模式,避免空字段开销
分布式支持
查询支持正则
动态扩展架构
32位的版本最多只能存储2.5GB的数据

一个数据项叫做 Document
一个文档嵌入另一个文档(comment 嵌入 post)叫做 Embed
储存一系列文档的地方叫做 Collections
表间关联,叫做 Reference
页: [1]
查看完整版本: python调用MongoDB使用心得