Python connects the mongodb operation data sample of of mongodb database configuration class
- 2020-04-02 13:20:37
- OfStack
I. relevant code
Database configuration class MongoDBConn. Py
#encoding=utf-8
'''
Mongo Conn The connection class
'''
import pymongo
class DBConn:
conn = None
servers = "mongodb://localhost:27017"
def connect(self):
self.conn = pymongo.Connection(self.servers)
def close(self):
return self.conn.disconnect()
def getConn(self):
return self.conn
MongoDemo. Py class
#encoding=utf-8
'''
Mongo operation Demo
Done:
'''
import MongoDBConn
dbconn = MongoDBConn.DBConn()
conn = None
lifeba_users = None
def process():
# Establish a connection
dbconn.connect()
global conn
conn = dbconn.getConn()
# list server_info information
print conn.server_info()
# List all databases
databases = conn.database_names()
print databases
# Delete libraries and tables
dropTable()
# Add database lifeba And table (collections)users
createTable()
# Insert data
insertDatas()
# Update the data
updateData()
# Query data
queryData()
# Delete the data
deleteData()
# Release the connection
dbconn.close()
def insertDatas():
datas=[{"name":"steven1","realname":" test 1","age":25},
{"name":"steven2","realname":" test 2","age":26},
{"name":"steven1","realname":" test 3","age":23}]
lifeba_users.insert(datas)
def updateData():
''' Modify only the last matched data
The first 3 Is set to True, Add one if the data is not found
The first 4 Is set to True, Multiple records are not updated
'''
lifeba_users.update({'name':'steven1'},{'$set':{'realname':' test 1 Modify the '}}, False,False)
def deleteData():
lifeba_users.remove({'name':'steven1'})
def queryData():
# Query all data
rows = lifeba_users.find()
printResult(rows)
# Query a data
print lifeba_users.find_one()
# Conditional query
printResult(lifeba_users.find({'name':'steven2'}))
printResult(lifeba_users.find({'name':{'$gt':25}}))
def createTable():
''' Create libraries and tables '''
global lifeba_users
lifeba_users = conn.lifeba.users
def dropTable():
''' Delete table '''
global conn
conn.drop_database("lifeba")
def printResult(rows):
for row in rows:
for key in row.keys():# Through the dictionary
print row[key], # add , Print without breaking lines
print ''
if __name__ == '__main__':
process()