使用Python 2.7 CURD 操作非关系型数据库MongoDB


在进行数据库的操作过程中,有些数据的格式没有关系,也即它是非关系型的时候,我们会用到非关系型数据库,

而MongoDB是一个由C++写的分布式非关系型数据库,目前应用比较成熟,稳定,API操作比较简单,目前支持Python 2.7,还没有支持Python 3.x的包。

以下是我使用Python 2.7操作MongoDB的一些例子:

1.访问本地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("Could 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 the

    # Connection object should it go out of scope. In most cases, keeping a

    # reference to the Database object for the lifetime of your program should

    # be sufficient.

    assert dbh.connection == c

   

   

   

    print "Successfully set up a database handle"

  

    if __name__ == "__main__":

        main()

 

 

2.插入操作:

'''

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("Could 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.更新操作


'''

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  更新操作

        # 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("Could not connect to MongoDB: %s" % e)

                sys.exit(1)

if __name__ == "__main__":

    main()


4.删除操作.


'''

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 documents are matched.

#            print "删除记录行的个数:\t"%count

           

    except ConnectionFailure, e:

                sys.stderr.write("Could not connect to MongoDB: %s" % e)

                sys.exit(1)

if __name__ == "__main__":

    main()


这些例子是参照 MongoDB & Python书箱写成的。

相关内容