This article describes how to connect to mongodb using python, including data insertion, Data Update, data query, and data deletion.
Database configuration class MongoDBConn. py
The code is as follows:
# Encoding = UTF-8
'''
Mongo Conn 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
Consumer Demo. py class
The code is as follows:
# 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
# Deleting databases and tables
DropTable ()
# Add database lifeba and table (collections) users
CreateTable ()
# Insert data
InsertDatas ()
# Update data
UpdateData ()
# Querying data
QueryData ()
# Deleting data
DeleteData ()
# Releasing a connection
Dbconn. close ()
Def insertDatas ():
Datas = [{"name": "Steven 1", "realname": "Test 1", "age": 25 },
{"Name": "Steven 2", "realname": "Test 2", "age": 26 },
{"Name": "Steven 1", "realname": "Test 3", "age": 23}]
Lifeba_users.insert (datas)
Def updateData ():
''' Only modifies the last matched data.
Set 3rd parameters to True. if this data is not found, add one
If the value of the first parameter is set to True, multiple records are not updated.
'''
Lifeba_users.update ({'name': 'Steven 1'}, {'$ set': {'realname': 'Test 1 modify'}, False, False)
Def deleteData ():
Lifeba_users.remove ({'name': 'Steven 1 '})
Def queryData ():
# Querying all data
Rows = lifeba_users.find ()
PrintResult (rows)
# Querying a data
Print lifeba_users.find_one ()
# Conditional query
PrintResult (lifeba_users.find ({'name': 'text2 '}))
PrintResult (lifeba_users.find ({'name': {'$ gt': 25 }}))
Def createTable ():
'''Create a database and a table '''
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 (): # traverse the dictionary
Print row [key], # Add, print without line breaks
Print''
If _ name _ = '_ main __':
Process ()