Python connection mongodb operation data example (mongodb database configuration class)

Time:2021-12-2
1. Database configuration class mongodbconn.py
#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
2. Ngodemo.py class
#encoding=utf-8
'''

Mongo operation demo
Done:
'''
import MongoDBConn

dbconn = MongoDBConn.DBConn()
conn = None
lifeba_users = None

def process():
    #Establish connection
    dbconn.connect()
    global conn
    conn = dbconn.getConn()

    #List servers_ Info information
    print conn.server_info()

    #List all databases
    databases = conn.database_names()
    print databases

    #Delete libraries and tables
    dropTable()
    #Add database lifeba and tables (collections) users
    createTable()
    #Insert data
    insertDatas()
    #Update data
    updateData()
    #Query data
    queryData()
    #Delete data
    deleteData()

    #Release connection
    dbconn.close()

def insertDatas():
    Data = [{"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():
    '' 'only modify the last matching data
           The third parameter is set to true. If the data is not found, add one
           If the fourth parameter is set to true, multiple records will not be updated
    '''
    lifeba_ Users. Update ({'name':'steven1 '}, {' $set ': {' realName ':' test 1 modify '}}, 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()
    #Query with condition
    printResult(lifeba_users.find({'name':'steven2'}))
    printResult(lifeba_users.find({'name':{'$gt':25}}))

def createTable():
    '' create library and 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], # plus, print without line breaks
        print ''

if __name__ == '__main__':
    process()