?
官方文档非常重要
http://api.mongodb.org/python/1.11/
http://www.mongodb.org/
?
这里我们是安装 pymongo
?
$easy_install pymongo 1、安装easy_install工具,它的作用类似于Php中的pear,或者Ruby中的gem,或者Perl中的cpan。 2、使用快捷的方法是使用ez_setup.py脚本: #wget -q http://peak.telecommunity.com/dist/ez_setup.py #python ez_setup.py 实例:比如说要安装Python的MySQL支持,可以执行如下命令,系统会自动在pypi网站列表里查找相关软件包: easy_install MySQL-python 这里我们是安装 pymongo easy_install pymongo 如果想删除通过easy_install安装的软件包,比如说:MySQL-python,可以执行命令: easy_install -m MySQL-python
?
?
一个例子
?
#coding=utf-8 from pymongo import Connection conn = Connection("localhost") db = conn.foo test = {"id":1, "novle":"测试一下"} db.foo.save(test) cursor = db.foo.find() for i in cursor: print i
?
?
带有权限认证的例子
?
#coding=utf-8 from pymongo import Connection,database conn = Connection("localhost") db = database.Database(conn,"foo") r = db.authenticate("test","123") print r cursor = db.foo.find() print cursor for i in cursor: print i
?
输出:
?
!python simple.py True <pymongo.cursor.Cursor object at 0x802858f90> {u'_id': ObjectId('4ee9a3aa283b6db0dc000000'), u'id': 1, u'novle': u'\u6d4b\u8bd5\u4e00\u4e0b'}
?
?
Django操作NOSQL(MongoDB)数据库
http://dmyz.org/archives/251
?
Django用mongodb入门例子
http://artori.us/use-mongodb-with-django/
?
安装这个 mongoengine 必须的
?
sudo easy_install mongoengine Searching for mongoengine Reading http://pypi.python.org/simple/mongoengine/ Reading http://hmarr.com/mongoengine/ Best match: mongoengine 0.5.2 Downloading http://pypi.python.org/packages/source/m/mongoengine/mongoengine-0.5.2.tar.gz#md5=3d7becee075cf3a3d2a88c85dd42b053 Processing mongoengine-0.5.2.tar.gz Running mongoengine-0.5.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-LUDBKj/mongoengine-0.5.2/egg-dist-tmp-Dpom4g 0.5.2 no previously-included directories found matching 'docs/_build' zip_safe flag not set; analyzing archive contents... Adding mongoengine 0.5.2 to easy-install.pth file Installed /usr/local/lib/python2.6/site-packages/mongoengine-0.5.2-py2.6.egg Processing dependencies for mongoengine Finished processing dependencies for mongoengine
?
?
创建一个 Django项目来测试
?
guanyu/branches/lidong/mongodb-tests]$ django-admin.py startproject mongodbtest cd mongodbtest $ python manage.py startapp helloworld
?
?
编辑3个文件
?*urls.py
?*helloworld/models.py
?*helloworld/views.py
?
urls.py
?
(r'^$','mongodbtest.helloworld.views.index'),
?
?
?
helloworld/models.py
?
#from django.db import models from mongoengine import * connect('test') class PhoneModel(Document): name = StringField(required=True) phone = StringField(max_length=50)
?
?
helloworld/views.py
?
from django.http import HttpResponse from models import PhoneModel def index(request): entry = PhoneModel(name='lidong') entry.phone = '13410320008' entry.save() resp = "hello %s , phone :%s" %(entry.name, entry.phone) return HttpResponse(resp)
?
?
检查数据库中的数据
?
$python >>> from pymongo import Connection >>> conn = Connection("localhost") >>> db = conn.test >>> db.collection