During database operations, some data formats are irrelevant, that is, when it is non-relational, we will use non-relational databases,
MongoDB is a distributed non-relational database written by C ++. Its Applications are mature, stable, and API operations are simple. Currently, it supports Python 2.7 and does not support Python 3. x package.
Here are some examples of using Python 2.7 to operate MongoDB:
1. Access Local MongoDB
'''
Created on 2011-11-30
@ Author: LONMID
'''
Import sys
From pymongo import Connection
From pymongo. errors import ConnectionFailure
Def main ():
Try:
C = Connection (host = "localhost", port = 27017)
Except ConnectionFailure, e:
Sys. stderr. write ("cocould not connect to MongoDB: % s" % e)
Sys. exit (1)
# Get a Database handle to a database named "mydb"
Dbh = c ["mydb"]
Dbh
# Demonstrate the db. connection property to retrieve a reference to
# Connection object shocould it go out of scope. In most cases, keeping
# Reference to the Database object for the lifetime of your program shocould
# Be sufficient.
Assert dbh. connection = c
Print "Successfully set up a database handle"
If _ name _ = "_ main __":
Main ()
2. insert operation:
'''
Created on 2011-11-30
@ Author: LONMID
'''
"An example of how to insert a document """
Import sys
From datetime import datetime
From pymongo import Connection
From pymongo. errors import ConnectionFailure
Def main ():
Try:
C = Connection (host = "localhost", port = 27017)
Except ConnectionFailure, e:
Sys. stderr. write ("cocould not connect to MongoDB: % s" % e)
Sys. exit (1)
Dbh = c ["mydb"]
Assert dbh. connection = c
User_doc = {
"Username": "janedoe ",
"Firstname": "Jane ",
"Surname": "Doe ",
"Dateofbirth": datetime (1974, 4, 12 ),
"Email": "janedoe74@example.com ",
"Score": 0
}
Dbh. users. insert (user_doc, safe = True)
Print "Successfully inserted document: % s" % user_doc
If _ name _ = "_ main __":
Main ()
3. Update operations
'''
Created on 2011-11-29
@ Author: LONMID
'''
Import sys
From pymongo import Connection
From pymongo. errors import ConnectionFailure
Import copy
Def main ():
Try:
Conn = Connection (host = "localhost", port = 27017)
Print ("Connected Localhost successfully !!!!! ")
Dbh = conn ["mydb"]
Assert dbh. connection = conn
Users = dbh. users. find_one ({"username": "janedoe "})
If not users:
Print "no document found for username janedoe"
# Else:
# For user in users:
# Print user. get ("username ")
Else:
For user in dbh. users. find (snapshot = True ):
Print user. get ("username ")
For user in dbh. users. find (snapshot = True ):
Print user. get ("email"), user. get ("score", 0)
Old_user_doc = dbh. users. find_one ({"username": "janedoe "})
New_user_doc = copy. deepcopy (old_user_doc)
# Modify the copy to change the email address
New_user_doc ["email"] = "janedoe74@example2.com"
# Run the update query update operation
# Replace the matched document with the contents of new_user_doc
Dbh. users. update ({"username": "janedoe"}, new_user_doc, safe = True)
Except ConnectionFailure, e:
Sys. stderr. write ("cocould not connect to MongoDB: % s" % e)
Sys. exit (1)
If _ name _ = "_ main __":
Main ()
4. delete operation.
'''
Created on 2011-11-29
@ Author: LONMID
'''
Import sys
From pymongo import Connection
From pymongo. errors import ConnectionFailure
Import copy
Def main ():
Try:
Conn = Connection (host = "localhost", port = 27017)
Print ("Connected Localhost successfully !!!!! ")
Dbh = conn ["mydb"]
Assert dbh. connection = conn
Users = dbh. users. find_one ({"username": "janedoe "})
If not users:
Print "no document found for username janedoe"
# Else:
# For user in users:
# Print user. get ("username ")
Else:
For user in dbh. users. find (snapshot = True ):
Print user. get ("username ")
For user in dbh. users. find (snapshot = True ):
Print user. get ("email"), user. get ("score", 0)
# Delete all documents in user collection with score 1
Dbh. users. remove ({"score": 1}, safe = True)
# Remove () will not raise any exception or error if no such ENTs are matched.
# Print "Number of deleted record rows: \ t" % count
Except ConnectionFailure, e:
Sys. stderr. write ("cocould not connect to MongoDB: % s" % e)
Sys. exit (1)
If _ name _ = "_ main __":
Main ()
These examples are written in the MongoDB & Python bookbox.