Example of using python to connect to mongodb for data operations (mongodb database configuration class)

Source: Internet
Author: User
Tags how to connect to mongodb
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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.