使用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书箱写成的。

学习链接:

http://api.mongodb.org/python/2.0.1/tutorial.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值