在进行数据库的操作过程中,有些数据的格式没有关系,也即它是非关系型的时候,我们会用到非关系型数据库,而MongoDB是一个由C++写的分布式非关系型数据库,目前应用比较成熟,稳定,API操作比较简单,目前支持Python 2.7,还没有支持Python 3.x的包。以下是我使用Python 2.7操作MongoDB的一些例子:1.访问本地MongoDB"""Created on 2011-11-30@author: LONMID"""import sysfrom pymongo import Connectionfrom pymongo.errors import ConnectionFailuredef 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 sysfrom datetime import datetimefrom pymongo import Connectionfrom pymongo.errors import ConnectionFailuredef 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 sysfrom pymongo import Connectionfrom pymongo.errors import ConnectionFailureimport copydef 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 sysfrom pymongo import Connectionfrom pymongo.errors import ConnectionFailureimport copydef 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 "删除记录行的个数: "%count except ConnectionFailure, e: sys.stderr.write("Could not connect to MongoDB: %s" % e) sys.exit(1)if __name__ == "__main__": main()
这些例子是参照 MongoDB & Python书箱写成的。Python 3.x之数据库框架Sqlalchemy操作SQlite(续)Ubuntu下编译安装MySQL双实例并配置主从复制相关资讯 python MongoDB
- Python 为什么要迁移到 Github (01月26日)
- Python 决定迁移到 GitHub (01月03日)
- 使用MongoDB C#官方驱动操作 (12/31/2015 16:27:56)
| - MongoDB 3.3.0 发布下载 (01月14日)
- MongoDB 3.2版WiredTiger存储引擎 (01月02日)
- 进程监控工具Supervisor 启动 (12/26/2015 10:49:57)
|
本文评论 查看全部评论 (0)