一,基本的连接、插入、查询操作
>>> import pymongo
>>> clnt=pymongo.Connection('10.0.10.205')
>>> db=clnt['lsy']
>>> collection=db.lzylzy
>>> abc={'name':'lzy'}
>>> collection.save(abc)
ObjectId('4ba868b31454320ea8000000')
>>> abc
{'_id': ObjectId('4ba868b31454320ea8000000'), 'name': 'lzy'}
>>> collection.database
Database(Connection('10.0.10.205', 27017), u'lsy')
>>> db.collection_names
>>> db.collection_names()
[u'lzylzy', u'system.indexes']
>>> collection.find_one()
{u'_id': ObjectId('4ba868b31454320ea8000000'), u'name': u'lzy'}
>>> r=[{'name':'jxq','sex':'male'},{'name':'wl','age':24}]
>>> collection.insert(r)
[ObjectId('4ba877521454320ea8000006'), ObjectId('4ba877521454320ea8000007')]
>>> x=collection.find()
>>> for i in x:
... print i
...
{u'_id': ObjectId('4ba868b31454320ea8000000'), u'name': u'lzy'}
{u'_id': ObjectId('4ba86a5b1454320ea8000001'), u'name': u'lsy'}
{u'_id': ObjectId('4ba86ab41454320ea8000002'), u'name': u'lsy'}
{u'_id': ObjectId('4ba86ae01454320ea8000003'), u'name': u'lsy'}
{u'_id': ObjectId('4ba86b231454320ea8000004'), u'name': u'pl'}
>>> type(x)
>>> collection.find_one({'name':'lsy'})
{u'_id': ObjectId('4ba86a5b1454320ea8000001'), u'name': u'lsy'}
二,简单删除操作
>>> for i in collection.find():
... print i
...
{u'_id': ObjectId('4ba868b31454320ea8000000'), u'name': u'lzy'}
{u'_id': ObjectId('4ba86a5b1454320ea8000001'), u'name': u'lsy'}
{u'_id': ObjectId('4ba86ab41454320ea8000002'), u'name': u'lsy'}
{u'_id': ObjectId('4ba86ae01454320ea8000003'), u'name': u'lsy'}
{u'age': 24, u'_id': ObjectId('4ba877521454320ea8000007'), u'name': u'wl'}
>>> collection.remove({'name':'lsy'})
>>> for i in collection.find():
... print i
...
{u'_id': ObjectId('4ba868b31454320ea8000000'), u'name': u'lzy'}
{u'age': 24, u'_id': ObjectId('4ba877521454320ea8000007'), u'name': u'wl'}
>>>
三,条件查询
>>> v=collection.find({"age":{'$lt':26}})
>>> for i in v:
... print i
...
{u'age': 24, u'_id': ObjectId('4ba877521454320ea8000007'), u'name': u'wl'}
四,使用索引
>>> collection.find({"age":{'$gt':23}}).sort('name').explain()['cursor']
u'BasicCursor'
>>> collection.find({"age":{'$gt':23}}).sort('name').explain()['nscanned']
7.0
>>> collection.create_index([('age',pymongo.DESCENDING),('name',pymongo.ASCENDING)])
u'age_-1_name_-1'
>>> collection.find({"age":{'$gt':23}}).sort('name').explain()['cursor']
u'BtreeCursor age_1_name_-1'
>>> collection.find({"age":{'$gt':23}}).sort('name').explain()['nscanned']
0.0
五,GridFS文件存取
>>> import pymongo
>>> import gridfs
>>> clnt=pymongo.Connection('10.0.10.205')
>>> db=clnt.gridfs_test#连接(如果不存在就创建)测试数据库
>>> fs=gridfs.GridFS(db)
>>> f=fs.open('test.exe','w')
>>> f.write(open(r'd:\tools\AdbeRdr90_zh_CN.exe','rb').read())
>>> f.close()
>>> f=fs.open('test.exe','r')
>>> open('c:/adf.exe','wb').write(f.read())
>>>