mongodb的python访问_python测试连接mongodb 简单读写

下载pymongo模块,测试机python为2.6.6

[2011-6-27 张子萌]

# wget http://pypi.python.org/packages/source/p/pymongo/pymongo-1.11.tar.gz

解压安装

# tar zxvf pymongo-1.11.tar.gz

# cd pymongo-1.11

# python setup.py install

安装比较简单,下面写一个脚本测试一下是否成功。返回的也是dict。

#!/usr/bin/python

#-*- coding:utf-8 -*-

import pymongo

conn = pymongo.Connection(“localhost”,27017)

db = conn.mytest

cursor = db.mytest.find()

for i in cursor:

print i

有结果就ok了。

a)测试1存取二进制

插入MP3试试看。首先上传一个test.mp3,然后把MP3转为二进制,最后入库。

#!/usr/bin/python

#-*- coding:utf-8 -*-

import pymongo

import bson

conn = pymongo.Connection(“localhost”,27017)

db = conn.mytest

get_mp3=open(‘test.mp3′,’rb’) #以二进制方法读取MP3

bin=bson.Binary(get_mp3.read()) #转换对象

db.mytest.save({“file_name”:”test_mp3″,”mp3″:bin}) #保存入库

get_mp3.close()

如库查询看到以下结果,MP3已经入库成功。

> db.mytest.find({},{file_name:1})

{ “_id” : ObjectId(“4e0a70d0b4a1024472000000”), “file_name” : “test_mp3” }

现在在把MP3读出来看看是否可以用。

#!/usr/bin/python

#-*- coding:utf-8 -*-

import pymongo

conn = pymongo.Connection(“localhost”,27017)

db = conn.mytest

cursor=db.mytest.find({“file_name” : “test_mp3”},{“mp3”:1})

file=open(‘123.mp3′,’wb’)

print >>file,cursor[0][“mp3”] #因为测试库中就有一首所以不用循环了

file.close

取出MP3试听是否成功。

b)测试2存取字符型。文本文件保存也可以用二进制,但是字符型更好,便于索引和

查找。

首先建立一个test.txt测试文本,内容如下:

first

second

three

four

用以下脚本入库

#!/usr/bin/python

#-*- coding:utf-8 -*-

import pymongo

conn = pymongo.Connection(“localhost”,27017)

db = conn.mytest

get_txt=open(‘test.txt’,’r’)

for line in get_txt: #也可以不用循环,将文件插入到一个值里

db.mytest.insert({“file_name”:”test_txt”,”content”:line})

get_txt.close()

入库完毕登录mongodb检查,结果如下:

> db.mytest.find({“file_name”:”test_txt”},{})

{ “_id” : ObjectId(“4e0a762bb4a1024508000000”), “content” : “firstn”, “file_name” : “test_txt” }

{ “_id” : ObjectId(“4e0a762bb4a1024508000001”), “content” : “secondn”, “file_name” : “test_txt” }

{ “_id” : ObjectId(“4e0a762bb4a1024508000002”), “content” : “threen”, “file_name” : “test_txt” }

{ “_id” : ObjectId(“4e0a762bb4a1024508000003”), “content” : “fourn”, “file_name” : “test_txt” }

现在在把文本读出来看看是否可以用。

#!/usr/bin/python

#-*- coding:utf-8 -*-

import pymongo

conn = pymongo.Connection(“localhost”,27017)

db = conn.mytest

cursor=db.mytest.find({“file_name” : “test_txt”},{“content”:1})

file=open(‘123.txt’,’a’)

for i in cursor:

print >>file,i[“content”]

file.close

查看文本已经输出,因为是追加,并且在库里保存了回车符“n”,所以输出的文件都会隔一行写一行。

http://api.mongodb.org/python/1.11/installation.html

http://pypi.python.org/pypi/pymongo/


版权声明:本文为weixin_30392607原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。