Python操作MongoDB
一、相关代码
数据库配置类 MongoDBConn.py
01 |
#encoding=utf-8 |
02 |
''' |
03 |
Created on 2012-11-12 |
04 |
|
05 |
@author: Steven http://www.lifeba.org |
06 |
|
07 |
Mongo Conn连接类 |
08 |
''' |
09 |
|
10 |
import pymongo |
11 |
|
12 |
class DBConn: |
13 |
conn = None |
14 |
servers = "mongodb://localhost:27017" |
15 |
|
16 |
def connect( self ): |
17 |
self .conn = pymongo.Connection( self .servers) |
18 |
|
19 |
def close( self ): |
20 |
return self .conn.disconnect() |
21 |
|
22 |
def getConn( self ): |
23 |
return self .conn |
MongoDemo.py 类
01 |
#encoding=utf-8 |
02 |
''' |
03 |
Created on 2012-11-12 |
04 |
|
05 |
@author: Steven http://www.lifeba.org |
06 |
|
07 |
Mongo操作Demo |
08 |
Done: |
09 |
''' |
10 |
import MongoDBConn |
11 |
|
12 |
dbconn = MongoDBConn.DBConn() |
13 |
conn = None |
14 |
lifeba_users = None |
15 |
|
16 |
def process(): |
17 |
#建立连接 |
18 |
dbconn.connect() |
19 |
global conn |
20 |
conn = dbconn.getConn() |
21 |
|
22 |
#列出server_info信息 |
23 |
print conn.server_info() |
24 |
|
25 |
#列出全部数据库 |
26 |
databases = conn.database_names() |
27 |
print databases |
28 |
|
29 |
#删除库和表 |
30 |
dropTable() |
31 |
#添加数据库lifeba及表(collections)users |
32 |
createTable() |
33 |
#插入数据 |
34 |
insertDatas() |
35 |
#更新数据 |
36 |
updateData() |
37 |
#查询数据 |
38 |
queryData() |
39 |
#删除数据 |
40 |
deleteData() |
41 |
|
42 |
#释放连接 |
43 |
dbconn.close() |
44 |
|
45 |
def insertDatas(): |
46 |
datas = [{ "name" : "steven1" , "realname" : "测试1" , "age" : 25 }, |
47 |
{ "name" : "steven2" , "realname" : "测试2" , "age" : 26 }, |
48 |
{ "name" : "steven1" , "realname" : "测试3" , "age" : 23 }] |
49 |
lifeba_users.insert(datas) |
50 |
|
51 |
def updateData(): |
52 |
'''只修改最后一条匹配到的数据 |
53 |
第3个参数设置为True,没找到该数据就添加一条 |
54 |
第4个参数设置为True,有多条记录就不更新 |
55 |
''' |
56 |
lifeba_users.update({ 'name' : 'steven1' },{ '$set' :{ 'realname' : '测试1修改' }}, False , False ) |
57 |
|
58 |
def deleteData(): |
59 |
lifeba_users.remove({ 'name' : 'steven1' }) |
60 |
|
61 |
def queryData(): |
62 |
#查询全部数据 |
63 |
rows = lifeba_users.find() |
64 |
printResult(rows) |
65 |
#查询一个数据 |
66 |
print lifeba_users.find_one() |
67 |
#带条件查询 |
68 |
printResult(lifeba_users.find({ 'name' : 'steven2' })) |
69 |
printResult(lifeba_users.find({ 'name' :{ '$gt' : 25 }})) |
70 |
|
71 |
def createTable(): |
72 |
'''创建库和表''' |
73 |
global lifeba_users |
74 |
lifeba_users = conn.lifeba.users |
75 |
|
76 |
def dropTable(): |
77 |
'''删除表''' |
78 |
global conn |
79 |
conn.drop_database( "lifeba" ) |
80 |
|
81 |
def printResult(rows): |
82 |
for row in rows: |
83 |
for key in row.keys(): #遍历字典 |
84 |
print row[key], #加, 不换行打印 |
85 |
print '' |
86 |
|
87 |
if __name__ = = '__main__' : |
88 |
出自:http://blog.snsgou.com/ |